用 jQuery 做滑鼠移入時高度展開、移出時收回的菜單,程式碼很短,但有一個幾乎每個人都會踩到的坑:快速來回移動滑鼠時,動畫會像堆疊積木一樣排隊播放,畫面變得極不聽話。解法就是 stop()。
<style>
body { font-size:12px; color:#fff; background:#000; }
.all ul { width:100%; text-align:center; }
.all ul li {
width:100%; height:40px; line-height:40px;
border-bottom:1px dashed #990066; cursor:pointer;
}
</style>
<div class="all">
<ul>
<li>第一項</li>
<li>第二項</li>
<li>第三項</li>
</ul>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.all ul li').mouseover(function () {
$(this).animate({ "height": "70px", "line-height": "70px" }, 100);
}).mouseleave(function () {
$(this).stop().animate({ "height": "40px", "line-height": "40px" }, 100);
});
});
</script>
只改 height,文字會貼在容器頂端,看起來像被裁掉。同時把 line-height 設成與 height 相同,文字就會垂直居中,視覺上才是「整塊均勻長高」。這是純 CSS 思維帶進 jQuery 動畫的小技巧。
jQuery 的動畫是佇列制的。當你快速把滑鼠移進移出五次,若不干預,就會產生十段動畫依序排隊,畫面變成「一格一格慢慢跳」,而且最後停在錯誤狀態。
stop() 的作用是清掉目前元素佇列中尚未執行的動畫。加上它之後,每次新的滑鼠事件都會先中止舊動畫再啟動新的,永遠只有一段動畫在跑,操作手感立刻變得跟手。
若動畫可能進行到一半被打斷,還常用兩個參數:
$(this).stop(true, false) // 第一個 true:連佇列一起清空;第二個 false:不跳到最終狀態
這裡用的是 mouseover,但它會在元素內的子元素之間移動時不斷觸發(因為事件會泡泡)。若元素內含其他標籤,比較恰當的選擇是 mouseenter,它只在真正進入元素邊界時觸發一次:
$('.all ul li').on({
mouseenter: function () { $(this).stop().animate({ height: '70px', lineHeight: '70px' }, 200); },
mouseleave: function () { $(this).stop().animate({ height: '40px', lineHeight: '40px' }, 200); }
});
順帶一提,在 jQuery 的 animate 參數中,CSS 屬性 line-height 可以寫成 lineHeight 駝峰式,也能寫成字串 'line-height',兩者都接受。
今天這類效果純 CSS 就足夠,而且效能更好(交給合成器處理,不佔主執行緒):
.all ul li { height:40px; line-height:40px; transition: height .2s ease; }
.all ul li:hover { height:70px; line-height:70px; }
jQuery 動畫的價值在於需要依據複雜條件決定要不要動、動到哪裡,或需要 callback 串接後續邏輯的場景;單純的狀態互動,CSS transition 永遠是更省電的選擇。