萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

jQuery 實現類 title 提示浮層:滑鼠懸停顯示詳細資訊完整範例

效果預覽

滑鼠移至列表項目,右側浮現詳細資訊卡片;移開自動隱藏。純 CSS 定位 + jQuery 事件綁定,無需額外插件。

HTML 結構

<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>

CSS 關鍵點

* { 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 微調,避免計算絕對座標的麻煩。

jQuery 交互邏輯

<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>
  • 使用 `mouseenter`/`mouseleave` 而非 `mouseover`/`mouseout`,避免子元素觸發冒泡導致閃爍。
  • `stop(true, true)` 清除動畫隊列,防止快速進出堆疊動畫。
  • 可改用 `hover()` 簡寫:`$items.hover(fnIn, fnOut)`。

進階增強

  • 動態定位:若列表靠近視窗邊緣,計算 `.show` 顯示區域是否超出視口,自動翻轉方向(`left` → `right`、`top` → `bottom`)。
  • 資料驅動渲染:`
  • `,JS 讀取資料動態生成 `.show` 內容,減少 HTML 體積。
  • 無障礙:加入 `tabindex="0"` 並處理 `focus`/`blur` 事件,支援鍵盤操作。
copyright © 萬盛學電腦網 all rights reserved