一个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); }; 这样,一个运动框架就写好了!原理很简单,不过还有待完善。慢慢来吧!
推荐阅读
不使用XMLHttpRequest实现异步加载 Iframe和script
调用页面如下: 复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">>>详细阅读
本文标题:JavaScript中的匀速运动和变速(缓冲)运动详细介绍
地址:http://www.17bianji.com/kaifa2/JS/22978.html
1/2 1