js is a method to achieve multiple motion effects on the same page

  • 2020-05-26 07:52:44
  • OfStack

This article illustrates how js can achieve multiple motion effects on the same page. Share with you for your reference. The specific analysis is as follows:

The principle of implementation is to add events to the loop of these five elements at the time of invocation. Note that the timer for each element needs to be separated.

Point 1:


var speed = (target - obj.offsetWidth)/8;

Buffering effect, 1 starts fast, then slows down until it stops


speed = speed>0?Math.ceil(speed):Math.floor(speed);

If the velocity is greater than 0, you round up, and if the velocity is less than 0, you round down.

Point 2:


if(obj.offsetWidth == target){
clearInterval(obj.timer);
}else{
obj.style.width = obj.offsetWidth+speed+"px";
}

The element width is compared to the target value, and if it is equal, turn off the timer; otherwise, the width continues to increase.

Point 3:


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);
}
}

Each element is assigned its own timer attribute, its own mouse event, and the motion function is called 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> Headless document </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 is helpful for you to design javascript program.


Related articles: