滑鼠移入觸發區域時,二級選單以滑動淡入動畫展開;滑鼠移出後延遲 250ms 自動收合,支援選單區域內滑鼠移動不閃爍。
<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 確保覆蓋其他元素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);
});
}
.stop() 防止動畫佇列堆疊使用者快速進出時,.stop() 會清除當前元素的動畫佇列,避免動畫疊加導致介面卡頓。
hover 綁定實現「不離開選單區域不收合」同時對觸發區域(theSpan)與選單本身(theMenu)綁定相同的 expand/collapse,滑鼠在兩區域間移動時不會觸發收合。
setTimeout 延遲收合提升使用體驗滑鼠瞬間離開邊界時不會立即收合,給予使用者 250ms 緩衝時間移回選單區域。
var tarHeight = theMenu.height() 取得選單實際高度,支援內容動態變化的選單高度自適應。
$(document).ready(function() {
dropMenu(".show"); // 針對所有 .show 元素啟用下拉選單
});
focusin/focusout)