滑鼠移入「分享」區塊,左側綠色面板滑出;移出則滑回隱藏。經典的側邊欄展開/收合動畫。

<div id="div1">
<span>分享到</span>
</div>
#div1 {
width: 150px; height: 200px;
background: green;
position: absolute;
left: -150px; /* 初始隱藏於視窗外 */
}
#div1 span {
position: absolute;
width: 20px; height: 60px;
line-height: 20px;
background: blue;
right: -20px; top: 70px;
cursor: pointer;
}
window.onload = function() {
var oDiv = document.getElementById('div1');
var timer = null;
oDiv.onmouseover = function() { startMove(0); };
oDiv.onmouseout = function() { startMove(-150); };
function startMove(iTarget) {
clearInterval(timer); // 關鍵:每次啟動前清除舊定時器
timer = setInterval(function() {
var speed = 0;
// 根據當前位置與目標位置決定速度方向
if (oDiv.offsetLeft > iTarget) {
speed = -10; // 向左移動
} else {
speed = 10; // 向右移動
}
// 到達目標位置則停止
if (oDiv.offsetLeft === iTarget) {
clearInterval(timer);
} else {
oDiv.style.left = oDiv.offsetLeft + speed + 'px';
}
}, 30);
}
};
iTarget,速度由邏輯自動推導,符合「呼叫者不關心過程」原則。clearInterval(timer) 確保同一時間只有一個定時器運行,防止重複點擊導致速度疊加。speed 不能整除距離,可能永遠無法 === 目標。改進:Math.abs(current - target) < Math.abs(speed) 直接設定目標值。requestAnimationFrame 替代 setInterval,配合 transform: translateX() 啟用 GPU 加速。「你叫計程車,只告訴司機目的地,不會指定時速 100 公里。動畫函式同理:傳目標,不傳速度。」