现在的位置: 首页 > 综合 > 正文

JavaScript中的匀速运动和变速(缓冲)运动

2012年11月02日 ⁄ 综合 ⁄ 共 1053字 ⁄ 字号 评论关闭

个人站点

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

比如匀速运动: 

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

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

匀速的比如: 

Javascript代码  收藏代码
  1. var timer=null;  
  2.   
  3. function startMove()  
  4. {  
  5.   
  6. var oDiv=document.getElementById('div1');  
  7. clearInterval(timer);  
  8. timer=setInterval(function () {  
  9. var iSpeed=1;  
  10.   
  11. if(oDiv.offsetLeft>=300)  
  12. {  
  13. clearInterval(timer);  
  14. }  
  15. else  
  16. {  
  17. oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';  
  18. }  
  19. },30);  
  20. };  

缓冲运动: 

Java代码  收藏代码
  1. var timer=null;  
  2. function startMove()  
  3. {  
  4. var iTarget=300;  
  5.   
  6. var oDiv=document.getElementById('div1');  
  7.   
  8. clearInterval(timer);  
  9. timer=setInterval(function () {  
  10. var iSpeed=(iTarget-oDiv.offsetLeft)/8;  
  11.   
  12. iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);  
  13.   
  14. iSpeed=Math.ceil(iSpeed);  
  15. if(oDiv.offsetLeft==iTarget)  
  16. {  
  17. clearInterval(timer);  
  18. }  
  19. else  
  20. {  
  21. oDiv.style.left=oDiv.offsetLeft+iSpeed+'px';  
  22. }  
  23. document.title=oDiv.style.left+' '+iSpeed;  
  24. },30);  
  25. };  


这样,一个运动框架就写好了!原理很简单,不过还有待完善。慢慢来吧!

抱歉!评论已关闭.