2015.7.19js-16(缓冲运动)

1.原理:利用speed = (目标值-初始值)/10;然后根据方向来判断是Math.ceil或Math.floor来取整。

JS

var oDiv = document.getElementById("wrap");
    var oBtn = document.getElementById("btn");
    var txt = document.getElementById("text");
    var timer = null

    oBtn.onclick = function(){
        clearInterval(timer);
        timer = setInterval(function(){
        var speed = (300 - oDiv.offsetLeft)/10;      //缓冲运动
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); //根据方向来判断取整。
        txt.value = oDiv.offsetLeft +"," + speed;
        oDiv.style.left = oDiv.offsetLeft +speed + "px";
        },Math.round(1000/60));        
    }

HTML

<style>
#wrap{width:100px;height:100px;background:red;position:absolute;left:0px;top:30px;}
#line{position: absolute;left:300px;top:0px;border:1px solid black;height:300px;}
</style>
<input type="button" id="btn" value="启动" />
<input type="text" id="text" />
<div id="wrap"></div>
<div id="line"></div>

 

posted @ 2015-07-20 22:05  AlanTao  阅读(161)  评论(0)    收藏  举报