鼠标拖拽窗口效果(不允许拖出屏幕的可视区域)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 <style> 8 #div1 { 9 width: 200px; 10 height: 200px; 11 background: #deb887; 12 position: absolute; 13 } 14 </style> 15 16 <script> 17 window.onload = function (){ 18 var oDiv = document.getElementById('div1') 19 var disX = 0; 20 var disY = 0; 21 22 oDiv.onmousedown = function (ev){ 23 console.log("23") 24 var oEvent = ev||event; 25 26 disX = oEvent.clientX - oDiv.offsetLeft; 27 disY = oEvent.clientY - oDiv.offsetTop; 28 document.onmousemove = function (ev){ 29 console.log("29") 30 var oEvent = ev||event; 31 var l = oEvent.clientX - disX; 32 var t = oEvent.clientY - disY; 33 //此处的判断是为了防止拖拽框被拖出屏幕可视区域 34 if(l<0) { 35 l=0; 36 }else if(l>document.documentElement.clientWidth - oDiv.offsetWidth){ 37 l = document.documentElement.clientWidth - oDiv.offsetWidth; 38 } 39 if(t<0) { 40 t=0; 41 }else if(t>document.documentElement.clientHeight- oDiv.offsetHeight){ 42 t = document.documentElement.clientHeight - oDiv.offsetHeight; 43 } 44 oDiv.style.left = l+ 'px'; 45 oDiv.style.top = t+ 'px'; 46 }; 47 //此处是为了防止在火狐浏览器下拖拽时会出现的两次阴影的效果,此处代码可以禁用 48 document.onmouseup = function (){ 49 console.log("49") 50 document.onmousemove = null; 51 document.onmouseup = null; 52 } 53 } 54 } 55 56 </script> 57 </head> 58 <body> 59 <div id="div1"></div> 60 </body> 61 </html>