js实现缓冲运动效果的方法
本文实例讲述了js实现缓冲运动效果的方法。分享给大家供大家参考。具体分析如下:
该实例可实现一开始速度很快,然后慢下来,直到停止的效果。
要点:
varspeed=(target-box.offsetLeft)/8;
目标点减去元素的当前位置的值除以8,因为offsetleft的值是一直在变大,所以速度的值也是一直的变小
speed=speed>0?Math.ceil(speed):Math.floor(speed);
正向速度的时候向上取整,反向速度的时候向下取整
代码:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="gb2312"/>
<title>无标题文档</title>
<style>
<!--
body{margin:0;padding:0;font:12px/1.5arial;}
#box{width:100px;height:100px;position:absolute;
background:#06c;left:0;}
-->
</style>
<script>
<!--
window.onload=function(){
varbox=document.getElementById("box");
varbtn=document.getElementById("btn");
vartimer=null;
btn.onclick=function(){
startrun(300);
}
functionstartrun(target){
clearInterval(timer);
timer=setInterval(function(){
varspeed=(target-box.offsetLeft)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(box.offsetLeft==target){
clearInterval(timer);
}else{
box.style.left=box.offsetLeft+speed+"px";
}
document.getElementById('abc').innerHTML+=box.offsetLeft+','+speed+'<br>';
},30);
}
}
//-->
</script>
</head>
<body>
<inputid="btn"type="submit"value="向右运动">
<divid="box">
</div>
<br>
<textareaid="abc"cols="50"rows="10"
style="margin-top:130px"></textarea>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。