js实现单元格拖拽效果
程序员文章站
2022-05-12 11:50:14
本文实例为大家分享了js实现单元格拖拽效果的具体代码,供大家参考,具体内容如下
本文实例为大家分享了js实现单元格拖拽效果的具体代码,供大家参考,具体内容如下
<head> <meta charset="utf-8"> <title></title> <style type="text/css"> * { margin: 0; padding: 0; } #box { position: relative; } #box div { position: absolute; width: 100px; height: 100px; border-radius: 15px; text-align: center; line-height: 100px; font-size: 50px; cursor: pointer; } </style> </head> <body> <div id="box"></div> <script type="text/javascript"> //生成结构 var odiv = document.getelementbyid("box"); var ml = mt = 10; //行列结构 for(var i = 0; i < 3; i++) { //行 for(var j = 0; j < 3; j++) { //列 var adiv = document.createelement("div"); odiv.appendchild(adiv); adiv.style.left = j * (adiv.offsetwidth + ml) + "px"; adiv.style.top = i * (adiv.offsetheight + mt) + "px"; //背景颜色随机 adiv.style.backgroundcolor = "rgb(" + math.floor(math.random() * 256) + "," + math.floor(math.random() * 256) + "," + math.floor(math.random() * 256) + ")"; //256=(256-0+1)+0; } } //添加文字 var str = "abcdefghi"; var aitems = odiv.children; for(var i = 0; i < str.length; i++) { aitems[i].innertext = str[i]; } //拖拽 for(var i = 0; i < aitems.length; i++) { aitems[i].onmousedown = function(e) { var evt = e || event; var x = evt.offsetx; var y = evt.offsetx; var dragnode = this; var clonenode = dragnode.clonenode(); odiv.replacechild(clonenode, dragnode); clonenode.style.border = "1px dashed #ccc"; odiv.appendchild(dragnode); dragnode.style.zindex = 1; document.onmousemove = function(e) { var evt = e || event; var _left = evt.clientx - x; var _top = evt.clienty - y; dragnode.style.left = _left + "px"; dragnode.style.top = _top + "px"; return false; //选中,文字也会拖动 去除默认行为 } document.onmouseup = function() { var disarr =[]; var newarr =[]; for(var i = 0; i < aitems.length-1; i++) { var disx = dragnode.offsetleft - aitems[i].offsetleft; var disy = dragnode.offsettop - aitems[i].offsettop; var dis= math.sqrt(math.pow(disx, 2) + math.pow(disy, 2)); disarr.push(dis); newarr.push(dis); } disarr.sort(function(a, b) { return a - b; }); var minval = disarr[0]; var minindex = newarr.indexof(minval); dragnode.style.left = aitems[minindex].style.left; dragnode.style.top = aitems[minindex].style.top; aitems[minindex].style.left = clonenode.style.left; aitems[minindex].style.top = clonenode.style.top; odiv.removechild(clonenode); document.onmousemove = null; document.onmouseup = null; } return false; } } </script> </body>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。