這是 JavaScript 動畫最入門的練習:點「向右」,方塊往右跑;點「向左」,方塊往左跑。用 setInterval 每隔一段時間改變元素的 left,就构成了最基本的位移動畫。
要點一:用当前位置與目標位置比較,決定方向。元素的左偏移量小於目標就正向移動,否則反向。
if (run.offsetLeft < target) {
speed = 2;
} else {
speed = -2;
}
要點二:到達目標就停止定時器。否則就讓当前位置加上速度值。
if (run.offsetLeft == target) {
clearInterval(timer);
} else {
run.style.left = run.offsetLeft + speed + "px";
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>左右運動</title>
<style>
body { margin:0; padding:0; }
#run {
width:100px; height:100px; background:#06c;
position:absolute; border:1px solid #000; left:0;
}
</style>
<script>
window.onload = function () {
var run = document.getElementById("run");
var btn = document.getElementById("btn");
var btn1 = document.getElementById("btn1");
var speed = 2;
var timer = null;
btn.onclick = function () { startrun(300); };
btn1.onclick = function () { startrun(0); };
function startrun(target) {
clearInterval(timer);
timer = setInterval(function () {
if (run.offsetLeft < target) { speed = 2; } else { speed = -2; }
if (run.offsetLeft == target) {
clearInterval(timer);
} else {
run.style.left = run.offsetLeft + speed + "px";
}
}, 30);
}
};
</script>
</head>
<body>
<input id="btn" type="button" value="運動向右">
<input id="btn1" type="button" value="運動向左">
<div id="run"></div>
</body>
</html>
同樣地,offsetLeft == target 的嚴格相等判斷依賴「距離剛好能被速度整除」。若起始位置與目標距離不是 speed 的倍數,元素會在目標兩側來回震盪。比較穩健的做法是改用「是否已越過目標」來判斷,例如檢查 Math.abs(target - run.offsetLeft) <= Math.abs(speed) 時直接對齊並停止。