js实现交换运动效果的方法
本文实例讲述了js实现交换运动效果的方法。分享给大家供大家参考。具体分析如下:
实现后的效果,点击互相交换位置和距离左边和上角的信息。
要点一:
varnow=s_pic_li[0]; for(vari=0;i<s_pic_li.length;i++){ s_pic_li[i].onclick=function(){ if(this==now)returnfalse; varw=now.offsetWidth; varh=now.offsetHeight; varl=now.offsetLeft; vart=now.offsetTop; varw1=this.offsetWidth; varh1=this.offsetHeight; varl1=this.offsetLeft; vart1=this.offsetTop; startrun(now,{width:w1,height:h1,left:l1,top:t1}); startrun(this,{width:w,height:h,left:l,top:t}); now=this; } }
循环给每一块加点击事件,获取交换双方的信息,然后执行运动函数,相关信息做为参数。
最后,上代码:
<!DOCTYPEhtml> <html> <head> <metacharset="gb2312"/> <title>无标题文档</title> <style> <!-- body,ul,li{margin:0;padding:0; font:18px/1.5arial;color:#333;} #big_pic{width:500px;height:400px; background:#ccc;text-align:center; position:absolute;} #s_picli{float:left;width:100px; height:80px;display:inline; background:#06c;text-align:center; position:absolute;top:310px;} --> </style> <script> <!-- window.onload=function(){ vars_pic=document.getElementById("s_pic"); vars_pic_li=s_pic.getElementsByTagName("li"); varnow=s_pic_li[0]; for(vari=0;i<s_pic_li.length;i++){ s_pic_li[i].onclick=function(){ if(this==now)returnfalse; varw=now.offsetWidth; varh=now.offsetHeight; varl=now.offsetLeft; vart=now.offsetTop; varw1=this.offsetWidth; varh1=this.offsetHeight; varl1=this.offsetLeft; vart1=this.offsetTop; startrun(now,{width:w1,height:h1,left:l1,top:t1}); startrun(this,{width:w,height:h,left:l,top:t}); now=this; } } } functiongetstyle(obj,name){ if(obj.currentStyle){ returnobj.currentStyle[name]; }else{ returngetComputedStyle(obj,false)[name]; } } functionstartrun(obj,json,fn){ clearInterval(obj.timer); obj.timer=setInterval(function(){ varisall=true; for(varattrinjson){ varcur=0; if(attr=="opacity"){ cur=Math.round(parseFloat(getstyle(obj,attr))*100); }else{ cur=parseInt(getstyle(obj,attr)); } varspeed=(json[attr]-cur)/8 speed=speed>0?Math.ceil(speed):Math.floor(speed); if(cur!=json[attr]){ isall=false; } if(attr=="opacity"){ obj.style.filter="alpha(opacity="+(cur+speed)+")"; obj.style.opacity=(cur+speed)/100; }else{ obj.style[attr]=cur+speed+"px"; } } if(isall){ clearInterval(obj.timer); if(fn){ fn(); } } },30); } //--> </script> </head> <body> <ulid="s_pic"> <listyle="left:0;top:0;width:400px;height:300px">0</div> <listyle="left:0;">1</li> <listyle="left:110px;">2</li> <listyle="left:220px;">3</li> <listyle="left:330px;">4</li> </ul> </body> </html>
希望本文所述对大家的javascript程序设计有所帮助。