頂部用戶頭像懸浮後展開「修改密碼/退出」菜單,是很常見的交互模式。這裡用 jQuery 實現一個帶高度與透明度漸變的版本,比直接 show/hide 自然得多。
<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>
注意 z-index:80000 這個細節——下拉菜單一定要浮在其他內容之上,否則會被下方元素遮擋。同時菜單初始設為 display:none,避免頁面載入時閃現。
function dropMenu(obj) {
$(obj).each(function () {
var theSpan = $(this);
var theMenu = theSpan.find(".drop");
var tarHeight = theMenu.height(); // 先量出真實高度
// 初始態:高度歸零、完全透明
theMenu.css({ height: 0, opacity: 0 });
var t1;
function expand() {
clearTimeout(t1);
theMenu.stop().show().animate(
{ height: tarHeight, opacity: 1 }, 200
);
}
function collapse() {
clearTimeout(t1);
t1 = setTimeout(function () {
theMenu.stop().animate(
{ height: 0, opacity: 0 }, 200,
function () {
$(this).css({ display: "none" });
}
);
}, 250);
}
// 同時監聽容器與菜單本身
theSpan.hover(expand, collapse);
theMenu.hover(expand, collapse);
});
}
延遲收起(250ms)是精華所在。鼠標從頭像移向菜單的過程中,難免會經過幾像素的空隙。如果菜單立刻收起,用戶根本來不及把光標移過去。加一個 250 毫秒的緩衝,這些「路過」的瞬間就被無視了,同時每次 expand 都會 clearTimeout 取消待執行的收起任務。
同時監聽父子元素。theSpan.hover() 和 theMenu.hover() 兩行都要寫,才能保證光標在菜單內部移動時不觸發收起。
stop() 防止動畫堆積。快速來回晃動鼠標時,如果不清空動畫隊列,動畫會一個接一個排隊播放,畫面變得極其怪異。stop() 會中止當前動畫並立即開始新的,是鏈式動畫的必備搭配。
先量高度再歸零。必須在設置 height:0 之前讀取 theMenu.height(),否則量到的就是 0。這個順序顛倒的錯誤非常經典。
如果項目對動畫細節要求不高,純 CSS 其實就能搞定,無需 JS:
.show { position: relative; }
.drop {
display: none;
position: absolute;
top: 100%;
right: 0;
}
.show:hover .drop { display: block; }
/* 想要淡入效果,改用過渡 */
.drop {
opacity: 0;
visibility: hidden;
transition: opacity .2s;
}
.show:hover .drop {
opacity: 1;
visibility: visible;
}
純 CSS 方案的好處是零 JS 開銷、天然流暢、不依賴任何庫。JS 方案的優勢則在於能加入延遲判斷、點擊外部關閉、鍵盤 ESC 關閉等更複雜的邏輯。選哪種取決於需求複雜度。