DOM操作-上移下移
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | *{ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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]; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步