做懸浮菜單時有個常見困擾:滑鼠稍微晃一下就移出了範圍,展開的層瞬間收掉,使用者很難點到里面的東西。解法是加上延遲——移入後等一下子才展開,移出後也等一下子才收起,中間若又移回來就取消收起的計時。
<div id="follow"> <a href="#" onmouseover="showPlusMobile();" onmouseout="hidePlusMobile();" class="btn">+Follow</a> <div class="layer_follow" id="layer_follow" onmouseover="showPlusMobile();" onmouseout="hidePlusMobile();"> <p>這是隱藏層</p> </div> </div>
注意隱藏層本身也掛了同一組事件。少了這一步,滑鼠從按鈕移進展開的層時會觸發外層的 mouseout,層就會被收掉。
.layer_follow
{
display:none
}
var isPlusMobileVisible = false;
var showTid;
var hideTid;
function showPlusMobile(){
if(isPlusMobileVisible == false) {
showTid = setTimeout("document.getElementById('layer_follow').style.display='block'; isPlusMobileVisible=true;", 500);
}else{
clearTimeout(hideTid); // 取消尚未執行的收起動作
}
}
function hidePlusMobile(){
if(isPlusMobileVisible == true) {
hideTid = setTimeout("document.getElementById('layer_follow').style.display='none'; isPlusMobileVisible=false;", 500);
}else {
clearTimeout(showTid); // 取消尚未執行的展開動作
}
}
整個互動靠兩個計時器 handle 與一個狀態旗標撐起來:showTid 負責延遲展開、hideTid 負責延遲收起,isPlusMobileVisible 記錄目前狀態。移入時若尚未展開就排程展開,若已展開則把待執行的收起取消;移出時反向操作。這樣滑鼠在按鈕與層之間來回移動時,計時器不斷被取消重排,層不會閃爍。
延遲 500 毫秒是一個常見的甜蜜點:夠快到感覺即時,又夠慢到容許滑鼠移動的誤差。若改用 jQuery,hover() 搭配 delay() 或 mouseenter/mouseleave 會更簡潔,但核心的「計時器互相取消」思路是一樣的。