富贵资源网 Design By www.hznty.com
本文实例为大家分享了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com
暂无评论...