滑鼠移入導航項,高度從 40px 平滑展開至 70px;移出時平滑收回。關鍵在於使用 .stop() 防止動畫隊列堆疊導致閃爍。
<div class="all">
<ul>
<li>第一項</li>
<li>第二項</li>
<li>第三項</li>
</ul>
</div>
.all ul { width:100%; text-align:center; }
.all ul li { width:100%; height:40px; line-height:40px; border-bottom:1px dashed #990066; cursor:pointer; }
$(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);
});
});
| 方法 | 作用 | 為何關鍵 |
|---|---|---|
.animate(props, duration) | 執行 CSS 屬性漸變動畫 | 原生實現高度/行高同步變化 |
.stop() | 停止當前正在執行的動畫 | 防止快速進出導致動畫隊列堆疊、元素反覆彈動 |
.mouseover/.mouseleave | 綁定進入/離開事件 | mouseleave 不冒泡,比 mouseout 更適合容器元素 |
transition: height 0.1s, line-height 0.1s;,效能更好、不佔用 JS 主執行緒。mouseenter 替代 mouseover:避免子元素觸發冒泡導致重複動畫。will-change: height, line-height; 或 transform: translateZ(0) 啟用 GPU。tabindex="0" 並處理 focus/blur,支援鍵盤操作。document.querySelectorAll('.all ul li').forEach(li => {
li.style.transition = 'height 0.1s, line-height 0.1s';
li.addEventListener('mouseenter', () => {
li.style.height = '70px';
li.style.lineHeight = '70px';
});
li.addEventListener('mouseleave', () => {
li.style.height = '40px';
li.style.lineHeight = '40px';
});
});
.stop() 是 jQuery 動畫開發的必備技巧,解決了早期動畫隊列堆疊的經典問題。現代開發建議優先使用 CSS Transition/Animation,僅在需複雜序列控制時使用 JS 動畫庫(如 GSAP、Anime.js)。