简单的修改了一下,让它自动吸附,原理很简单,判断t,l的距离,只要让它在小于一个距离的时候距离变为0 就可以了
带边框的自动吸附的拖拽代码如下:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'/> <title>带框的吸附拖拽</title> <style> *{margin:0;padding:0;} #div1{width:100px; height:100px; position:absolute; background:red;cursor:move;overflow:hidden;border-radius:8px;} .div2{border:1px dotted #333;position:absolute;border-radius:8px;} </style> <script> window.onload=function(){ var oDiv=document.getElementById("div1"); var disX=disY=0; oDiv.onmousedown=function(event){ var event=event || window.event; disX=event.clientX-oDiv.offsetLeft; //判断鼠标在div的X轴位置 disY=event.clientY-oDiv.offsetTop; //判断鼠标在div的y轴的位置 var oBox=document.createElement("div"); oBox.className="div2"; oBox.style.width=(oDiv.offsetWidth-2)+"px";//为oBox的宽赋值 oBox.style.height=(oDiv.offsetHeight-2)+"px"; //为oBox 的高赋值 oBox.style.left=oDiv.offsetLeft+"px";//oBox的初始位置 oBox.style.top=oDiv.offsetTop+"px"; document.body.appendChild(oBox); if(oDiv.setCapture){ //兼容ie的事件捕获 oDiv.onmousemove=move; oDiv.onmouseup=up; oDiv.setCapture(); }else{ document.onmousemove=move; //兼容ff chrome document.onmouseup=up; } function move(event){ var event=event||window.event; var l=event.clientX-disX; var t=event.clientY-disY; if(l<50){ l=0; }else if(l>(document.documentElement.clientWidth-oBox.offsetWidth-50)){ l=document.documentElement.clientWidth-oBox.offsetWidth; } if(t<50){ t=0; }else if(t>(document.documentElement.clientHeight-oBox.offsetHeight-50)){ t=document.documentElement.clientHeight-oBox.offsetHeight; } oBox.style.left=l+"px"; oBox.style.top=t+"px"; } function up(){ oDiv.style.left=oBox.offsetLeft+'px'; oDiv.style.top=oBox.offsetTop+'px'; document.body.removeChild(oBox); this.onmousemove=null; this.onmouseup=null; if(oDiv.releaseCapture){ oDiv.releaseCapture(); } } return false; }; } </script> </head> <body> <div id="div1"></div> </body> </html>