需求:点击当前元素,看看是否有上个兄弟节点或者下个兄弟节点,如果有就让他们依次下落(当前元素也会下落),否则就不用下落
HTML
<div id="box"></div>
CSS
#box{ position: relative; margin: 20px auto; } #box div{ 50px; height: 50px; background: red; position: absolute; top: 0px; }
JS
var Box=document.getElementById("box"); var aDiv=Box.getElementsByTagName("div"); var num=0; var num1=0; var timer=null; var timer1=null; //生成div for (var i=0;i<10;i++) { Box.innerHTML+="<div style='left:"+i*60+"px;'></div>"; } for (var i=0;i<aDiv.length;i++) { aDiv[i].index=i; aDiv[i].onclick=function(){ //用两个变量保存点击的div的下标 num1=num=this.index; //被点击的div先往下运动 moveTo(aDiv[num],"top",200,10); //然后被点击的div两侧的div依次往下掉落 //控制被点击的div右边的div下落 if(this.index<9){ timer=setInterval(function(){ if(num>=8){ clearInterval(timer); } num++; moveTo(aDiv[num],"top",200,10); },500) } //控制被点击的div左边的div下落 if(this.index>0){ timer1=setInterval(function(){ if(num1<=1){ clearInterval(timer1); } num1--; moveTo(aDiv[num1],"top",200,10); },500) } } } //运动函数 function moveTo(obj,attr,target,dir,endFn){ clearInterval(obj.timer); dir=parseInt(getStyle(obj,attr))<target?dir:-dir; obj.timer=setInterval(function(){ var speed=parseInt(getStyle(obj,attr))+dir; if(speed>target&&dir>0||speed<target&&dir<0){ speed=target; } obj.style[attr]=speed+"px"; //清除定时器 if(speed==target){ clearInterval(obj.timer); if(endFn){ endFn(); } } },30) } //获得元素样式 function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle[attr]; }else{ return getComputedStyle(obj)[attr]; } }