This article describes the method of pure JS to simulate elastic motion of div layer. Share it for your reference. The details are as follows:
characteristic:
1. Supports customization of various constants
2. Theory supports all elements, just modify it, you understand
3. Known support browsers: chrome/firefox/IE7, 8, 9
<html> <head> <meta http-equiv=Content-Type content="text/html;charset=utf-8"> <script type="text/javascript"> var a=900;//Maximum distancevar b;//Timer variablevar c=-1;//Next click on the direction of motion -1 Negative motion 1 Positive motionvar d=2; //Rebound constant The larger the value, the smaller the elasticity. Take the value d>1var e=-1; //The current direction of movementvar f=a; //Current locationvar g=0; //One-directional movement timevar h; //Elastomervar i=15;//The greater the movement speed, the slower the movementfunction Bounce(id){ h=(id); //End unfinished motion if(b)clearInterval(b); //Reset time g=0; c=-1*c; //Next click on the movement direction to change b=setInterval('move()',i); } function move(){ if(c==1){ if(e==-1){ if(f-(2*g-1)>0){ f=f-(2*g-1); g++; }else{ e=1; f=1; g++; g=parseInt(g/d); g=g%2==0?(g+1):g; if(g==3)clearInterval(b); } }else{ if(g>0){ g--; f=f+2*g-1; }else{ e=-1; g=0; } } =()+"px"; }else{ if(e==1){ if(f+(2*g-1)<a){ f=f+(2*g-1); g++; }else{ e=-1; f=a; g++; g=parseInt(g/d); g=g%2==0?(g+1):g; if(g==1)clearInterval(b); } }else{ if(g>0){ g--; f=f-(2*g-1); }else{ e=1; g=0; } } =()+"px"; } } </script> </head> <body> <div style="color:red;font-size:12px;text-align:center;"> <div style="text-align:left;color:green;margin:50px 300px;"> characteristic:<br> * Supports customization of various constants <br> * Theory supports all elements,Just modify,You understand<br> * Known support for browsers:chrome/firefox/IE7、8、9 </div> </div> <input type="button" value="click me" onClick="Bounce('test');" style="text-align:center;border:1px #ccc solid;padding:5px 10px;margin:0px 200px 100px 200px;"/> <div style="width:900px;height:200px;margin:0px 200px;background-color:#e8e8e8;border:1px #ccc solid;" onClick="Bounce('test');"></div> </body> </html>
I hope this article will be helpful to everyone's JavaScript programming.