javascript拖拽
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>拖拽</title> </head> <style> #div1{width: 200px;height: 200px;background-color: red;position: absolute; padding:30px;border: 2px solid #000000;} .box{border: 1px dashed black;position: absolute;} </style> <body> <div id="div1"></div> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); var disX=0,disY=0; oDiv.onmousedown = function(ev){ var oEvent = ev||event; disX = oEvent.clientX - oDiv.offsetLeft; disY = oEvent.clientY - oDiv.offsetTop; var oBox = document.createElement("div"); oBox.className = "box"; oBox.style.width = oDiv.offsetWidth-2 + "px";//减去边框 oBox.style.height = oDiv.offsetHeight-2 + "px"; //下面两行防止div移动后再次点击时会自动生成一个在原div位置的虚线框 oBox.style.left = oDiv.offsetLeft + "px"; oBox.style.top = oDiv.offsetTop + "px"; document.body.appendChild(oBox); document.onmousemove = function(ev){ var oEvent = ev||event; var l = oEvent.clientX-disX; var t = oEvent.clientY-disY; //这里可以用来做磁性吸附 if(l<0){l = 0;}else if(l>document.documentElement.clientWidth - oDiv.offsetWidth){ l = document.documentElement.clientWidth - oDiv.offsetWidth; } if(t<0){t = 0;}else if(t>document.documentElement.clientHeight - oDiv.offsetHeight){ t = document.documentElement.clientHeight - oDiv.offsetHeight;} oBox.style.left = l + "px"; oBox.style.top = t + "px"; } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; oDiv.style.left = oBox.offsetLeft+"px"; oDiv.style.top = oBox.offsetTop+"px"; document.body.removeChild(oBox); } return false;//firefox某些版本下会出现鬼影现象,阻止默认事件(浏览器bug) } } </script> </body> </html>