DOM操作-上移下移
HTML
<ul> <li style="top: 0;"> <span>啦啦啦啦</span> <i>1</i> <input type="button" name="" id="" value="上移" /> <input type="button" name="" id="" value="下移" /> </li> <li style="top: 50px;"> <span>哈哈哈哈</span> <i>2</i> <input type="button" name="" id="" value="上移" /> <input type="button" name="" id="" value="下移" /> </li> <li style="top: 100px;"> <span>呱呱呱呱</span> <i>3</i> <input type="button" name="" id="" value="上移" /> <input type="button" name="" id="" value="下移" /> </li> <li style="top: 150px;"> <span>小小小小</span> <i>4</i> <input type="button" name="" id="" value="上移" /> <input type="button" name="" id="" value="下移" /> </li> </ul>
CSS
*{ margin: 0; padding: 0; } ul{ position: relative; } li{ height: 50px; position: absolute; line-height: 50px; /*margin: 10px 0;*/ left: 0; } li i{ font-style: normal; }
JS
var Btn=document.getElementsByTagName("input"); var oUl=document.getElementsByTagName("ul")[0]; var timer=null; for (var i=0;i<Btn.length;i++) { Btn[i].index=i; Btn[i].onclick=function(){ var parent=this.parentNode; var pre=this.parentNode.previousElementSibling; var next=this.parentNode.nextElementSibling; clearInterval(timer); //获得和保存该元素父级的定位初始值,准备与变换的值进行对比,当差值等于50px时清除定时器,停止运动 var oldSpeed=parseInt(getStyle(parent,"top")); if(this.index%2==0){ //上移 if(this.parentNode ==oUl.firstElementChild){ alert("到头了"); }else{ //元素交换 oUl.insertBefore(parent, pre); timer=setInterval(function(){ //获得该元素的定位值 var speed=parseInt(getStyle(parent,"top")); //上移定位置递减 speed--; //获得此元素的上一个元素的定位值 var speed1=parseInt(getStyle(pre,"top")); //下移定位置递增 speed1++; //当差值等于50时清除定时器 if(oldSpeed-speed==50){ clearInterval(timer); } parent.style.top=speed+"px"; pre.style.top=speed1+"px"; },30) } }else{ //下移 if(this.parentNode == oUl.lastElementChild){ alert("到尾了"); }else{ //元素交换 oUl.insertBefore(parent,next.nextElementSibling); timer=setInterval(function(){ //获得该元素的定位值 var speed=parseInt(getStyle(parent,"top")); //下移定位值递增 speed++; //获得此元素的上一个元素的定位值 var speed1=parseInt(getStyle(next,"top")); //上移定位值递减 speed1--; //当差值等于50时清除定时器 if(speed-oldSpeed==50){ clearInterval(timer); } parent.style.top=speed+"px"; next.style.top=speed1+"px"; },30) } } } } function getStyle(obj,attr ){ if(obj.currentStyle){ return obj.currentStyle(attr); }else{ return getComputedStyle(obj)[attr]; } }