Home >Web Front-end >JS Tutorial >js method to achieve multiple motion effects on the same page_javascript skills
The example in this article describes the method of using js to achieve multiple motion effects on the same page. Share it with everyone for your reference. The specific analysis is as follows:
The implementation principle is to add events to these five elements in a loop when calling. Note that the timers for each element need to be separate.
Point 1:
var speed = (target - obj.offsetWidth)/8;
Buffer motion effect, very fast at first, then slower and slower until it stops
speed = speed>0?Math.ceil(speed):Math.floor(speed);
If the speed is greater than 0, round up, if the speed is less than 0, round down.
Point 2:
if(obj.offsetWidth == target){ clearInterval(obj.timer); }else{ obj.style.width = obj.offsetWidth+speed+"px"; }
Compare the element width with the target value. If they are equal, close the timer. Otherwise, the width continues to increase.
Point three:
for(i=0; i<runs_li.length; i++){ runs_li[i].timer = null; runs_li[i].onmouseover = function(){ startrun(this,300); } runs_li[i].onmouseout = function(){ startrun(this,80); } }
Add its own timer attribute and mouse event to each element, and call the motion function in the mouse event.
Finally, add the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style> body,ul,li{margin:0; padding:0;} #runs li{width:80px; height:80px; background:#06c; list-style:none; position:absolute; left:0;} </style> <script> window.onload = function(){ var runs = document.getElementById("runs"); var runs_li = runs.getElementsByTagName("li"); var i=0; for(i=0; i<runs_li.length; i++){ runs_li[i].timer = null; runs_li[i].onmouseover = function(){ startrun(this,300); } runs_li[i].onmouseout = function(){ startrun(this,80); } } } function startrun(obj,target){ clearInterval(obj.timer); obj.timer = setInterval(function(){ var speed = (target - obj.offsetWidth)/8; speed = speed>0?Math.ceil(speed):Math.floor(speed); if(obj.offsetWidth == target){ clearInterval(obj.timer); }else{ obj.style.width = obj.offsetWidth+speed+"px"; } document.title = obj.offsetWidth + ',' + target; },30); } </script> </head> <body> <ul id="runs"> <li style="top:0">1</li> <li style="top:90px;">2</li> <li style="top:180px;">3</li> <li style="top:270px;">4</li> <li style="top:360px;">5</li> </ul> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.