固定寬度 319px 的側邊欄預藏於視窗左側 (left: -320px)。滑鼠移入滑出顯示 (left: 0),移出滑回隱藏。右側標籤 span 固定於側邊欄右緣,隨面板移動。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>側邊欄動畫</title>
<style>
#div1 { width:319px; height:340px; border:1px solid #FFF; position:absolute; top:100px; left:-320px; background:url(images/1.png) no-repeat; }
#div1 span { width:30px; height:130px; position:absolute; right:-23px; top:95px; background:red; color:#FFF; text-align:center; line-height:40px; border-radius:0 200px 200px 0; font-family:"微軟雅黑"; }
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById("div1");
var time = null, speed = 8;
oDiv.onmouseover = function() {
clearInterval(time);
time = setInterval(function() {
if (oDiv.offsetLeft >= 0) { clearInterval(time); }
else { oDiv.style.left = oDiv.offsetLeft + speed + 'px'; }
}, 1);
};
oDiv.onmouseout = function() {
clearInterval(time);
time = setInterval(function() {
if (oDiv.offsetLeft <= -320) { clearInterval(time); }
else { oDiv.style.left = oDiv.offsetLeft - speed + 'px'; }
}, 1);
};
};
</script></head>
<body>
<div id="div1"><span>分享到</span></div>
</body></html>
<script>
window.onload = function() {
var oDiv = document.getElementById("div1");
var time = null, spe = 8, speed = null;
function move(targetLeft) {
clearInterval(time);
time = setInterval(function() {
if (oDiv.offsetLeft > targetLeft) speed = -spe;
else speed = spe;
if (oDiv.offsetLeft === targetLeft) { clearInterval(time); }
else { oDiv.style.left = oDiv.offsetLeft + speed + 'px'; }
}, 1);
}
oDiv.onmouseover = function() { move(0); };
oDiv.onmouseout = function() { move(-320); };
};
</script>
clearInterval 防止多重疊加導致加速失控。offsetLeft 獲取當前位置,配合目標值控制方向與停止條件。speed,簡單高效;進階可改用緩動函式 (ease-out) 提升手感。onmouseover/out 綁在整個 div1 上,包含標籤區域,避免滑鼠進入標籤觸發 mouseout 導致閃爍。transition: left 0.3s ease,JS 僅切換 class,效能更佳、程式碼極簡。requestAnimationFrame 實現平滑幀動畫。new Sidebar({trigger: 'hover', direction: 'left', width: 320})。此範例展示傳統 JS 定時器動畫的核心邏輯:位置插值、邊界檢測、定時器生命週期管理。理解這些基礎,有助於深入掌握現代動畫庫(如 GSAP、Anime.js)的底層原理。