您的位置:首页 > Web前端 > JavaScript

JavaScript中的匀速运动和变速(缓冲)运动详细介绍

2012-11-11 00:00 1011 查看
一个div的运动其实就是它与浏览器边框的距离在变动。如果他变化的速率一定,那就是匀速运动;如果变化的速率不一定,那么就是变速运动。当,变化率与聚离浏览器边框的距离成比例的话,那么就可以说是div在做缓冲运动。
其实,很简单,就是用一个定时器(timer),每隔一段时间来改变div聚浏览器边框的距离。

比如匀速运动:

进入定时器:(每隔30ms做)
if(是否到达终点)
{ 停止定时器}
else do{ 改变距离}

改变距离的方法决定是匀速还是变速(缓冲)运动。

匀速的比如:
var timer=null; 
function startMove() 
{ 

var oDiv=document.getElementById('div1'); 
clearInterval(timer); 
timer=setInterval(function () { 
var iSpeed=1; 

if(oDiv.offsetLeft>=300) 
{ 
clearInterval(timer); 
} 
else 
{ 
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px'; 
} 
},30); 
};


缓冲运动:
var timer=null; 
function startMove() 
{ 
var iTarget=300; 

var oDiv=document.getElementById('div1'); 

clearInterval(timer); 
timer=setInterval(function () { 
var iSpeed=(iTarget-oDiv.offsetLeft)/8; 

iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed); 

iSpeed=Math.ceil(iSpeed); 
if(oDiv.offsetLeft==iTarget) 
{ 
clearInterval(timer); 
} 
else 
{ 
oDiv.style.left=oDiv.offsetLeft+iSpeed+'px'; 
} 
document.title=oDiv.style.left+' '+iSpeed; 
},30); 
};

这样,一个运动框架就写好了!原理很简单,不过还有待完善。慢慢来吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: