这篇文章主要介绍“JavaScript如何实现九宫格拖拽效果”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“JavaScript如何实现九宫格拖拽效果”文章能帮助大家解决问题。
代码如下:
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> body{ margin: 0; padding: 0; } #wrap{ position: relative; } #wrap div{ position: absolute; width: 100px; height: 100px; font-size: 50px; text-align: center; line-height: 100px; border-radius: 10px; } </style> </head> <body> <div id="wrap"></div> <script type="text/javascript"> //生成结构 var oWrap = document.getElementById("wrap"); var mt = ml = 10; for(var i = 0; i < 3; i++){ for(var j = 0; j < 3; j++){ var oDiv = document.createElement("div"); oWrap.appendChild(oDiv); oDiv.style.top = i*(oDiv.offsetHeight + mt) + "px"; oDiv.style.left = j*(oDiv.offsetWidth + ml) + "px"; oDiv.style.backgroundColor = "rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")" } } var arr = "ABCDEFGHI"; var aItems = oWrap.children; var len = aItems.length; for(var i = 0; i < aItems.length; i++){ aItems[i].innerHTML = arr[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.offsetY; var _this = this; var cloneNode = this.cloneNode(); cloneNode.style.border = '1px dashed #cecece'; this.style.zIndex = 1; oWrap.replaceChild(cloneNode,this); oWrap.appendChild(this); document.onmousemove = function(e){ var evt = e || event; var _left = evt.clientX - x - oWrap.offsetLeft; var _top = evt.clientY - y - oWrap.offsetTop; _this.style.left = _left + "px"; _this.style.top = _top + "px"; return false; } document.onmouseup = function(){ //交换位置 var disArr = []; var newArr = []; console.log(aItems.length); for(var i = 0; i < len; i++){ var disX = _this.offsetLeft - aItems[i].offsetLeft; var disY = _this.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 minIndex = newArr.indexOf(disArr[0]); _this.style.left = aItems[minIndex].style.left; _this.style.top = aItems[minIndex].style.top; aItems[minIndex].style.left = cloneNode.style.left; aItems[minIndex].style.top = cloneNode.style.top; oWrap.removeChild(cloneNode); document.onmousemove = null; document.onmouseup = null; } } } </script> </body></html>
效果图
关于“JavaScript如何实现九宫格拖拽效果”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网行业资讯频道,小编每天都会为大家更新不同的知识点。