緩衝運動是多物件動畫的基礎。以下示範讓多個方塊各自獨立移動,並說明與單物件版本的差別。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" charset="utf-8" />
<meta http-equiv="content-type" content="text/html" />
<title>demo</title>
</head>
<body>
<div id="odiv" style="position:absolute;width:200px;height:200px;background:red;left:0;"></div>
<div id="odiv1" style="position:absolute;width:200px;height:200px;background:red;left:0;top:250px;"></div>
<script type="text/javascript">
var odiv=document.getElementById('odiv');
var odiv1=document.getElementById('odiv1');
odiv.onclick=function(){
move(odiv,500);
}
odiv1.onclick=function(){
move(odiv1,500);
}
function move(obj,target){
clearInterval(dt);
var dt=setInterval(function(){
var ol=parseInt(obj.style.left);
if(ol==target){
clearInterval(dt);
}else{
var speed=(target-ol)/8;
speed>0?speed=Math.ceil(speed):speed=Math.floor(speed);
obj.style.left=ol+speed+"px";
}
},30);
}
</script>
</body>
</html>
出發點是:動畫腳本必須知道「現在是哪個物件在動」。所以運動函式除了目標值 iTarget,還要多收一個 obj 參數。
更重要的是計時器不能共用。如果所有元素共用同一個計時器變數,當 A 還沒運動完就滑到 B,B 的 clearInterval 會把 A 的動畫一起掐掉,畫面就會卡住。把計時器掛在元素身上(obj.timer)就能徹底解決這個衝突。
此外,緩衝運動離不開取整。速度 (target - cur) / 8 通常會算出小數,若不取整,物件會永遠差幾分之一像素而到不了終點,導致計時器清不掉、動畫停不下來。程式碼中用 Math.ceil 與 Math.floor 依方向取整,就是為了保證最後一步能精準落在目標點上。
歸納起來,多物件運動的三條原則是:函式要多收 obj 參數、計時器要綁在物件上、速度一定要取整。