onmousedown:存储距离
onmousemove:根据距离,计算div最新位置
问题1:当鼠标移动过快脱离div,此时div不会跟随鼠标移动
解决:改为document.onmouseover
问题2:当鼠标移动div超出浏览器可视区范围,此时找不到div
解决:应判断div是否移动超出可视区范围,若超出,则将div的左边距置为0,右边和顶部底部同理
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script type="text/javascript"> 6 window.onload=function(){ 7 var oDiv1=document.getElementById("div1"); 8 var disX=0; 9 var disY=0; 10 oDiv1.onmousedown=function(ev){ 11 oEvent=ev||event; 12 disX=oEvent.clientX-oDiv1.offsetLeft; 13 disY=oEvent.clientY-oDiv1.offsetTop; 14 document.onmousemove=function(ev){ 15 oEvent=ev||event; 16 var l=oEvent.clientX-disX; 17 var t=oEvent.clientY-disY; 18 //判断用户拖拽是否拖出浏览器可视区 19 if(l<0) 20 l=0; 21 else if(l>document.documentElement.clientWidth-oDiv1.offsetWidth) 22 l=document.documentElement.clientWidth-oDiv1.offsetWidth; 23 if(t<0) 24 t=0; 25 else if(t>document.documentElement.clientHeight-oDiv1.offsetHeight) 26 t=document.documentElement.clientHeight-oDiv1.offsetHeight; 27 28 oDiv1.style.left=l+'px'; 29 oDiv1.style.top=t+'px'; 30 }; 31 document.onmouseup=function(){ 32 document.onmousemove='null'; 33 document.onmouseup='null'; 34 } 35 return false; 36 }; 37 }; 38 </script> 39 <style> 40 41 #div1{ 42 width:100px; 43 height:80px; 44 background:#ccc; 45 position:absolute; 46 } 47 48 </style> 49 </head> 50 <body> 51 <div id="div1"></div> 52 53 </body> 54 </html>