Accelerated motion, that is, an object moving faster and faster, deceleration movement, that is, an object moving faster and slower. 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 movement after the increase in speed, so that the effect of accelerated movement appears, deceleration movement is the same truth.
Here are two examples:
Accelerated movement
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>javascript Accelerated Movement </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>
Note: In this example, when you click Go, the div block will do the acceleration movement to the right
Deceleration movement
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>javascript Deceleration Movement </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>
Note: In this example, when you click Go, the div block continues to decelerate to the right until the speed is reduced to zero, the speed becomes negative, and then the left is done to accelerate the motion.