滑鼠移至列表項目,右側浮現詳細資訊卡片;移開自動隱藏。純 CSS 定位 + jQuery 事件綁定,無需額外插件。
<div class="wrap">
<ul class="list clearfix">
<li>
<a href="#">UI 設計師</a>
<div class="show">
<p>所屬部門:技術部</p>
<p>工作地點:鄭州</p>
<p>招聘人數:21</p>
</div>
</li>
<!-- 更多 li 重複結構 -->
</ul>
</div>
* { margin:0; padding:0; }
body { font-size:12px; }
.wrap { width:600px; margin:100px auto; }
.clearfix:after { content:""; display:table; clear:both; }
.list { position: relative; } /* 關鍵:作為絕對定位參考父層 */
.list li {
list-style:none; width:100px; height:24px; line-height:24px;
margin-right:10px; float:left;
}
.list li a { text-decoration:none; color:#333; display:block; }
.list li a:hover { text-decoration:underline; color:#F00; }
.show {
position: absolute;
width: 100px;
background: #FFFFE1;
border: 1px solid #ffcc01;
padding: 6px;
display: none; /* 預設隱藏 */
z-index: 5;
margin-top: 10px; /* 相對 li 定位向下偏移 */
margin-left: 60px; /* 相對 li 定位向右偏移 */
}
.show p { height:18px; line-height:18px; }
**為何用 `margin-top/left` 而非 `top/left`?**
配合 `position:absolute` 且無 `top/left` 時,元素會停留在「正常流中的原位置」,再用 margin 微調,避免計算絕對座標的麻煩。
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
var $items = $(".wrap").find("li");
$items.on("mouseenter", function() {
$(this).find(".show").stop(true, true).fadeIn(150); // 防抖動
}).on("mouseleave", function() {
$(this).find(".show").stop(true, true).fadeOut(100);
});
});
</script>