主要是將物體的速度由大變小,到達目標位置的時候,停止。
緩衝運動框架:
1.關閉定時器
2.開啓定時器
3.速度的計算:速度=(目標位置-物體的位置)/係數
4.速度取整:
5.判斷
function startmove(iTarget){
clearInterval(timer);
timer=setInterval(function(){
var speed=(iTarget-oDiv.offsetLeft)/5;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(oDiv.offsetLeft==iTarget){
clearInterval(timer);
}else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30)
}
例如:
html:
<div id="div1">
<div id="div2"></div>
<div id="div3">分享到</div>
</div>
css:
#div1{ position:absolute;left:-200px; }
#div1 div{width:200px; height:200px; background:red;float:left;}
#div1 #div3{background:blue;color:#fff;width:30px; text-align:center; padding:50px 0; height:auto; margin-top:30px; }
js:
var timer=null;
var oDiv=document.getElementById("div1");
function startmove(iTarget){
clearInterval(timer);
timer=setInterval(function(){
var speed=(iTarget-oDiv.offsetLeft)/5;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(oDiv.offsetLeft==iTarget){
clearInterval(timer);
}else{
oDiv.style.left=oDiv.offsetLeft+speed+'px';
}
},30)
}
oDiv.οnmοuseοver=function(){
startmove(0);
}
oDiv.οnmοuseοut=function(){
startmove(-200);
}