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