The example in this article describes the method of simulating the elastic movement of the div layer using pure js. Share it with everyone for your reference. The details are as follows:
Features:
1. Supports customization of various constants
2. The theory supports all elements, just modify style.width, you know
3. Known supported 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;//最大距离 var b;//定时器变量 var c=-1;//下次点击运动方向 -1负向运动 1正向运动 var d=2; //反弹常量 数值越大弹性越小 取值d>1 var e=-1; //当前运动方向 var f=a; //当前位置 var g=0; //已单向运动时间 var h; //弹性体 var i=15;//运动速度 数值越大,运动越慢 function Bounce(id){ h=document.getElementById(id); //终止未完成的运动 if(b)clearInterval(b); //重置时间 g=0; c=-1*c; //下次点击运动方向改变 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; } } h.style.width=f.toString()+"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; } } h.style.width=f.toString()+"px"; } } </script> </head> <body> <div style="color:red;font-size:12px;text-align:center;"> <div style="text-align:left;color:green;margin:50px 300px;"> 特性:<br> * 支持各项常数自定义 <br> * 理论支持所有元素,只需修改style.width,你懂得<br> * 已知支持浏览器: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;" id="test" onClick="Bounce('test');"></div> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.