Javascript模拟加速运动与减速运动代码分享
加速运动,即一个物体运动时速度越来越快;减速运动,即一个物体运动时速度越来越慢。现在用Javascript来模拟这两个效果,原理就是用setInterval或setTimeout动态改变一个元素与另外一个元素的距离,如xxx.style.left或xxx.style.marginLeft,然后每次运动后都使速度增加,这样加速运动的效果就出现了,减速运动是同样的道理。
下面是两个示例:
加速运动
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>Javascript加速运动</title>
<styletype="text/css">
*{margin:0;padding:0;}
.div1{width:100px;height:100px;background:#f60url(qiuweiguan.gif)no-repeatcentercenter;}
</style>
<scripttype="text/javascript">
var$$=function(id){
returndocument.getElementById(id);
}
window.onload=function(){
varoBtn=$$("btn1");
varoDiv=$$("div1");
vartimer=null;
varspeed=0;
oBtn.onclick=function(){
clearInterval(timer);
timer=setInterval(function(){
speed++;
oDiv.style.marginLeft=oDiv.offsetLeft+speed+"px";
},30);
}
}
</script>
</head>
<bodyid="body">
<buttonid="btn1"class="btn1">GO</button>
<divid="div1"class="div1"></div>
</body>
</html>
注:本示例中,点击GO后,div块会一直向右做加速运动
减速运动
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>Javascript减速运动</title>
<styletype="text/css">
*{margin:0;padding:0;}
.div1{width:100px;height:100px;background:#f60url(qiuweiguan.gif)no-repeatcentercenter;}
</style>
<scripttype="text/javascript">
var$$=function(id){
returndocument.getElementById(id);
}
window.onload=function(){ varoBtn=$$("btn1"); varoDiv=$$("div1"); vartimer=null; varspeed=30; oBtn.onclick=function(){ clearInterval(timer); timer=setInterval(function(){ speed—; oDiv.style.marginLeft=oDiv.offsetLeft+speed+"px"; },30); } } </script> </head> <bodyid="body"> <buttonid="btn1"class="btn1">GO</button> <divid="div1"class="div1"></div> </body> </html>