思路简介:
1.当鼠标点击事件发生后,创建一个新的一模一样的div;
2.利用鼠标事件属性设置新div跟随移动;
3.通过计算与某个div距离最近来实现交换效果;
纯属自我巩固,有大佬有新的思路。希望能随时给我点拨,您的一句提醒对于我很有受用。
<style>#box { width: 303px; height: 303px; margin: 100px auto; }#box div { width: 100px; height: 100px; float: left; margin-left: 1px; margin-top: 1px; text-align: center; line-height: 100px; font-size: 50px; color: #FFF; }#box div:nth-of-type(1) { background: #000; } #box div:nth-of-type(2) { background: #f00; } #box div:nth-of-type(3) { background: #0f0; } #box div:nth-of-type(4) { background: #00f; } #box div:nth-of-type(5) { background: #ff0; } #box div:nth-of-type(6) { background: #f0f; } #box div:nth-of-type(7) { background: #0ff; } #box div:nth-of-type(8) { background: pink; } #box div:nth-of-type(9) { background: orange; } #box .draging { position: absolute; }
</style><body><div id="box"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div></div><script>let divs = document.querySelectorAll('#box div');let box = document.querySelector('#box')for(var i=0;i<divs.length;i++){var oDiv = divs[i];//当点击的时候创建一个div 可以进行拖拽 //最后交换的divoDiv.onmousedown = function(e){//最后交换的divlet that = this;// let offsetX = e.offsetX; let offsetY = e.offsetY;//cloneNode(true)赋值元素 (如果参数为true,同时赋值子元素)
let dragDiv = this.cloneNode(true); console.log(dragDiv);
//box.appendChild(dragDiv);
dragDiv.className = 'draging'dragDiv.style.backgroundColor = getComputedStyle(this).backgroundColor;//让新生成的div出现在自己的位置上console.log(this.offsetLeft); console.log(this.offsetTop); dragDiv.style.left = this.offsetLeft+'px'; dragDiv.style.top = this.offsetTop +'px';//跟随移动
document.onmousemove = function(evt){ let x= evt.pageX - offsetX; let y= evt.pageY - offsetY ; dragDiv.style.left = x+'px'; dragDiv.style.top = y +'px'; return false } document.onmouseup = function(){ document.onmousemove =null//离谁的距离最近;选择排序let min = distance(divs[0],dragDiv); let minIndex = 0; for(var i=0;i<divs.length;i++){ var oDiv = divs[i];//oDiv dragdiv的距离;勾股定理;let c = distance(oDiv,dragDiv); console.log(c); if (c<min){ min = c; minIndex = i; } console.log(min,minIndex); } console.log(min,minIndex);//互相交换内容和样式 和最小的div//that 和 min的交换let minDiv = divs[minIndex]; let tmpText = that.innerHTML; that.innerHTML = minDiv.innerHTML minDiv.innerHTML = tmpText; let tmpBg = getComputedStyle(that).backgroundColor that.style.backgroundColor = getComputedStyle(minDiv).backgroundColor; minDiv.style.backgroundColor = tmpBg; dragDiv.remove(); } return false; } }//把他封装成函数
function distance(oDiv,dragDiv){//oDiv dragdiv的距离;勾股定理;let a = oDiv.offsetLeft -dragDiv.offsetLeft; let b = oDiv.offsetTop-dragDiv.offsetTop; let c = Math.sqrt(a*a +b*b); return c; }</script></body>