Accelerating motion, that is, an object moving faster and faster, slowing down, that is, when an object moves more and more slowly. Now, using JavaScript to simulate these two effects, the principle is to use setinterval or settimeout to dynamically change the distance between an element and another element, such as Xxx.style.left or xxx.style.marginLeft, and then each time after each movement to increase the speed, so that the effect of accelerated motion appears, deceleration movement is the same reason.
Here are two examples:
Accelerated motion
[HTML]
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>javascript Accelerated Sports </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>
<body id = "Body" >
<button id= "btn1" class= "BTN1" >GO</button>
<div id= "Div1" class= "Div1" ></div>
</body>
[/html]
Example demonstration and source code download for accelerated motion
Demo Download
Note: In this example, when you click Go, the div block will always move to the right to accelerate the movement
Deceleration movement
[HTML]
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>javascript Slow Motion </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>
<body id = "Body" >
<button id= "btn1" class= "BTN1" >GO</button>
<div id= "Div1" class= "Div1" ></div>
</body>
[/html]
Example demonstration and source code download for deceleration movement
Demo Download
Note: In this example, after clicking Go, the div block will slow down to the right until the speed is reduced to zero, the velocity becomes negative, and then the acceleration moves to the left.
JavaScript acceleration motion and deceleration motion