點擊文字觸發動畫,div 選單從寬高 0 以 50px/25px 步長放大至 200×100px,滑鼠移出 2.1 秒後自動縮小消失,滑鼠移入取消自動關閉,體驗細膩自然。
w、h 記錄當前寬高。fnLarge():每 10ms 遞增寬高,直到達標,形成展開動畫。fnSmall():每 5ms 遞減寬高,歸零後 display:none,形成收合動畫。setTimeout 遞迴驅動,簡單高效。<script>
var w = 0, h = 0, mout;
function emotion() {
var menu = document.getElementById('menu');
if (w <= 50) { menu.style.display = 'block'; fnLarge(); }
else { fnSmall(); }
}
function fnLarge() {
var menu = document.getElementById('menu');
if (w < 200) { w += 50; h += 25; menu.style.width = w + 'px'; menu.style.height = h + 'px'; setTimeout(fnLarge, 10); }
}
function fnSmall() {
var menu = document.getElementById('menu');
if (w > 0) { w -= 50; h -= 25; menu.style.width = w + 'px'; menu.style.height = h + 'px'; setTimeout(fnSmall, 5); }
else { menu.style.display = 'none'; }
}
</script>
<style>
#menu { border:2px solid #666; background:#fff; margin:5px auto; overflow:hidden; display:none; padding:5px 10px; }
li { list-style:none; width:70px; }
li.title { font-weight:bold; }
</style>
<p onclick="emotion()" style="cursor:pointer;font-size:24px;display:inline;">點擊這行文字試試!</p>
<div id="menu" onmouseout="mout=setTimeout('fnSmall()',2111);" onmouseover="clearTimeout(mout);">
<table><tr>
<td><ul><li class="title">ASP</li><li><a href="#" onclick="fnSmall()">新聞</a></li>...</ul></td>
<td><ul><li class="title">PHP</li>...</ul></td>
<td><ul><li class="title">JSP</li>...</ul></td>
</tr></table>
</div>
// 使用 CSS transition + class 切換,效能更好、程式碼更簡潔
#menu { transition: width 0.3s, height 0.3s, opacity 0.3s; opacity: 0; pointer-events: none; }
#menu.open { width: 200px; height: 100px; opacity: 1; pointer-events: auto; }
// JS 僅切換 class
menu.classList.toggle('open');
// 滑鼠離開延遲關閉
menu.addEventListener('mouseleave', () => closeTimer = setTimeout(() => menu.classList.remove('open'), 2100));
menu.addEventListener('mouseenter', () => clearTimeout(closeTimer));
利用瀏覽器原生合成器加速動畫,主執行緒不被阻塞,行動裝置表現更佳。