Javascript simulated acceleration and deceleration code sharing, javascript deceleration
Acceleration means that an object is moving faster and faster. Deceleration means that an object is moving slowly. Now we use 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 increase the speed after each movement, so that the effect of the accelerated movement will appear, and the deceleration movement is the same principle.
The following are two examples:
Acceleration
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Javascript acceleration </title>
<Style type = "text/css">
* {Margin: 0; padding: 0 ;}
. Div1 {width: 100px; height: 100px; background: # f60 url(qiuweiguan.gif) no-repeat 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>
Note: In this example, after you click GO, The div block continues to accelerate to the right.
Deceleration
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> Javascript slowdown </title>
<Style type = "text/css">
* {Margin: 0; padding: 0 ;}
. Div1 {width: 100px; height: 100px; background: # f60 url(qiuweiguan.gif) no-repeat 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>
Note: In this example, after you click GO, The div block continues to slow down to the right until the speed is reduced to zero, the speed changes to a negative value, and then to the left for acceleration.