萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實作滑鼠懸浮顯示二級選單下拉動畫效果

效果預覽

滑鼠移入觸發區域時,二級選單以滑動淡入動畫展開;滑鼠移出後延遲 250ms 自動收合,支援選單區域內滑鼠移動不閃爍。

HTML 結構佈局

<div class="show">
    <img src="~/images/head_icon.png" />
    <div class="drop" style="display:none; z-index:80000" id="profileMenu">
        <ul>
            <li><a class="pass" style="cursor: pointer" href='#'><span>修改密碼</span></a></li>
            <li><a class="quit" style="cursor: pointer" href='#'><span>退出</span></a></li>
        </ul>
    </div>
</div>
  • .show:觸發區域(如使用者頭像區塊)
  • .drop:隱藏的二級選單容器,預設 display:none、高 z-index 確保覆蓋其他元素

jQuery 控制邏輯

function dropMenu(obj) {
    $(obj).each(function () {
        var theSpan = $(this);
        var theMenu = theSpan.find(".drop");
        var tarHeight = theMenu.height();
        
        // 初始狀態:高度 0、透明度 0
        theMenu.css({ height: 0, opacity: 0 });
        
        var t1; // 計時器變數
        
        // 展開動畫
        function expand() {
            clearTimeout(t1);
            theMenu.stop().show().animate({ 
                height: tarHeight, 
                opacity: 1 
            }, 200);
        }
        
        // 收合動畫(延遲 250ms 執行,避免誤觸)
        function collapse() {
            clearTimeout(t1);
            t1 = setTimeout(function () {
                theMenu.stop().animate({ 
                    height: 0, 
                    opacity: 0 
                }, 200, function () {
                    $(this).css({ display: "none" });
                });
            }, 250);
        }
        
        // 同時綁定觸發區域與選單區域的 hover 事件
        theSpan.hover(expand, collapse);
        theMenu.hover(expand, collapse);
    });
}

關鍵技術點解析

1. .stop() 防止動畫佇列堆疊

使用者快速進出時,.stop() 會清除當前元素的動畫佇列,避免動畫疊加導致介面卡頓。

2. 雙重 hover 綁定實現「不離開選單區域不收合」

同時對觸發區域(theSpan)與選單本身(theMenu)綁定相同的 expand/collapse,滑鼠在兩區域間移動時不會觸發收合。

3. setTimeout 延遲收合提升使用體驗

滑鼠瞬間離開邊界時不會立即收合,給予使用者 250ms 緩衝時間移回選單區域。

4. 動態計算目標高度

var tarHeight = theMenu.height() 取得選單實際高度,支援內容動態變化的選單高度自適應。

使用方式

$(document).ready(function() {
    dropMenu(".show"); // 針對所有 .show 元素啟用下拉選單
});

擴充建議

  • 加入鍵盤無障礙支援(focusin/focusout)
  • 選單項目點擊後自動收合
  • 響應式斷點下改為點擊展開模式
copyright © 萬盛學電腦網 all rights reserved