1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 #div1{width: 100px;height:100px;background-color:red;position: absolute;} 8 .box{border:1px dashed black; position: absolute;} 9 </style> 10 <script> 11 window.onload=function(){ 12 var oDiv=document.getElementById('div1'); 13 var disX=0; 14 var disY=0; 15 16 oDiv.onmousedown=function(ev){ 17 var oEvent=ev||event; 18 19 disX=oEvent.clientX-oDiv.offsetLeft; 20 dixY=oEvent.clientY-oDiv.offsetTop; 21 22 var oBox=document.createElement('div'); 23 oBox.className='box'; 24 oBox.style.width=oDiv.offsetWidth-2+'px'; 25 oBox.style.height=oDiv.offsetHeight-2+'px'; 26 27 oBox.style.left=oDiv.offsetLeft+'px'; 28 oBox.style.top=oDiv.offsetTop+'px'; 29 30 document.body.appendChild(oBox); 31 32 document.onmousemove=function(ev){ 33 var oEvent=ev||event; 34 var l=oEvent.clientX-disX; 35 var t=oEvent.clientY-disY; 36 37 oBox.style.left=l+'px'; 38 oBox.style.top=t+'px'; 39 } 40 41 document.onmouseup=function(ev){ 42 document.onmousemove=null; 43 document.onmouseup=null; 44 45 oDiv.style.left=oBox.offsetLeft+'px'; 46 oDiv.style.top=oBox.offsetTop+'px'; 47 document.body.removeChild(oBox); 48 } 49 50 return false; 51 } 52 } 53 </script> 54 </head> 55 <body> 56 <div id="div1"> 57 </div> 58 </body> 59 </html>