一個圓形區塊在容器內持續移動,碰到邊界就折返,搭配「開始 / 停止」兩個按鈕控制。這是早期網頁廣告最常見的動態效果,實作核心是 setInterval 定時改寫座標。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>移動特效</title>
<style>
.box2{ width:200px; height:200px; background:red; border-radius:50%; position:relative; }
.box3{ width:800px; height:500px; border:1px solid red; }
</style>
</head>
<body>
<button type="button" id="start">開始</button>
<button type="button" id="stop">停止</button>
<div class="box3">
<div id="box" class="box2"></div>
</div>
<script type="text/javascript">
var lr = 600, tb = 300; // 左右、上下邊界
var i = 0, j = 0; // 目前座標
var box = document.getElementById('box');
var start = document.getElementById('start');
var stop = document.getElementById('stop');
start.onclick = function(){
start.style.display = 'none';
stop.style.display = 'inline';
var time = setInterval(function(){
box.style.left = i + 'px';
box.style.top = j + 'px';
if (i > lr) { lr = 0; i--; } else { lr = 600; i++; }
if (j > tb) { tb = 0; j--; } else { tb = 300; j++; }
stop.onclick = function(){
clearInterval(time);
stop.style.display = 'none';
start.style.display = 'inline';
};
}, 5);
};
</script>
</body>
</html>
移動靠的是「每 5 毫秒把 left / top 各加減 1」,而折返則用一組上下界變數 lr 與 tb 控制:當座標超過上界,就把邊界設為 0 並改為遞減;遞減到 0 再把邊界設回 600(或 300)並改為遞增。這樣一來一往,就形成反覆彈跳的路徑。
停止的關鍵是 clearInterval(time),把計時器編號清掉,迴圈自然不再執行。
原範例為了求簡,有幾處值得優化:
transform: translate() 只觸發合成,不必重排(reflow),效能好很多。stop.onclick,雖然能動但多此一舉。另外提醒,這類自動移動的橫幅若做為廣告投放,多數平台與無障礙規範都要求提供暫停機制,並且避免閃爍頻率過高,這也是範例中「停止」按鈕存在的意義。