標籤:style blog http 使用 os width
基本思路:使用定時器讓物體向右運動,在運動的過程中再不是勻速運動,而是先快後慢,即距離越大,速度越快,距離越小,速度越小,但是到達終點的時候,必須注意要使用向上取整函數Math.ceil()和向下取整函數Math.floor();這樣才能夠正確無誤地到達終點,而不是有出入。
<!DOCTYPE HTML><!----><html><head><meta charset="utf-8"><title></title><style>#div1{width:100px;height:100px;background:red;position:absolute;left:0px;//left:600px;top:50px;}#div2{width:1px;height:300px;background:red;position:absolute;left:300px;top:0px;background:black;}</style> <script>function startMove(){var oDiv=document.getElementById('div1');setInterval(function(){var speed=(300-oDiv.offsetLeft)/10;speed=speed>0?Math.ceil(speed):Math.floor(speed);//向上取整oDiv.style.left=oDiv.offsetLeft+speed+'px';document.title=oDiv.offsetLeft+','+speed;},30);}</script></head><body> <input type="button" value="開始運動" onclick="startMove()"/> <div id="div1"></div> <div id="div2">/<div></body></html>:
初始狀態,分別從左出發和從右出發:
沒取整導致有出入的情況,title表示終點位置和速度大小:
取整沒誤差情況: