SoFunction
Updated on 2025-02-28

How to achieve the exchange of motion effects by js

This article describes the method of JS to achieve exchange motion effects. Share it for your reference. The specific analysis is as follows:

After realizing the effect, click to exchange information on the position and distance to the left and upper corners with each other.

Key Point 1:

var now = s_pic_li[0];
for(var i=0; i<s_pic_li.length; i++){
s_pic_li[i].onclick = function(){
if(this == now) return false;
var w = ;
var h = ;
var l = ;
var t = ;
var w1= ;
var h1 = ;
var l1 = ;
var t1 = ;
startrun(now,{width:w1,height:h1,left:l1,top:t1});
startrun(this,{width:w,height:h,left:l,top:t});
now=this;
}
}

The loop adds a click event to each piece, obtains the information of both parties involved, and then executes the motion function, and the relevant information is used as parameters.

Finally, the code above:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset="gb2312" /&gt;
&lt;title&gt;Untitled document&lt;/title&gt;
&lt;style&gt;
&lt;!--
body,ul,li{margin:0; padding:0;
font:18px/1.5 arial; color:#333;}
#big_pic{width:500px; height:400px;
background:#ccc; text-align:center;
position:absolute;}
#s_pic li{float:left; width:100px;
height:80px; display:inline;
background:#06c; text-align:center;
position:absolute; top:310px;}
--&gt;
&lt;/style&gt;
&lt;script&gt;
&lt;!--
 = function(){
 var s_pic = ("s_pic");
 var s_pic_li = s_pic.getElementsByTagName("li");
 var now = s_pic_li[0];
 for(var i=0; i&lt;s_pic_li.length; i++){
  s_pic_li[i].onclick = function(){
   if(this == now) return false;
   var w = ;
   var h = ;
   var l = ;
   var t = ;
   var w1= ;
   var h1 = ;
   var l1 = ;
   var t1 = ;
   startrun(now,{width:w1,height:h1,left:l1,top:t1});
   startrun(this,{width:w,height:h,left:l,top:t});
   now=this;
  }
 }
}
function getstyle(obj,name){
 if(){
  return [name];
 }else{
  return getComputedStyle(obj,false)[name];
 }
}
function startrun(obj,json,fn){
 clearInterval();
  = setInterval(function(){
  var isall = true; 
  for(var attr in json){
   var cur=0;
   if(attr == "opacity"){
    cur = (parseFloat(getstyle(obj,attr))*100);
   }else{
    cur = parseInt(getstyle(obj,attr));
   }
   var speed = (json[attr] - cur)/8
   speed = speed&gt;0?(speed):(speed);
   if(cur != json[attr]){
    isall = false;
   }
   if(attr == "opacity"){
     = "alpha(opacity="+(cur+speed)+")";
     = (cur+speed)/100;
   }else{
    [attr] = cur+speed+"px";
   }
  }
  if(isall){
   clearInterval();
   if(fn){
    fn();
   }
  }
 },30);
}
//--&gt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;ul &gt;
 &lt;li style="left:0; top:0; width:400px; height:300px"&gt;0&lt;/div&gt;
 &lt;li style="left:0;"&gt;1&lt;/li&gt;
 &lt;li style="left:110px;"&gt;2&lt;/li&gt;
 &lt;li style="left:220px;"&gt;3&lt;/li&gt;
 &lt;li style="left:330px;"&gt;4&lt;/li&gt;
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;

I hope this article will be helpful to everyone's JavaScript programming.