限制范围的拖拽
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> #div1{ width: 100px; height: 100px; background: red; position: absolute; } #img1{ position: absolute; } </style> <script> window.onload=function(){ var oDiv=document.getElementById("div1"); var oImg=document.getElementById("img1"); drag(oImg); drag(oDiv); function drag(obj){ obj.onmousedown = function(ev){ var ev = ev || event; var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop; if(obj.setCapture){ obj.setCapture(); } document.onmousemove = function(ev){ var ev = ev || event; var L = ev.clientX-disX; var T = ev.clientY-disY; if(L < 0){ L = 0; //可视区域的宽度-当前对象的宽度 }else if(L > document.documentElement.clientWidth - obj.offsetWidth){ L = document.documentElement.clientWidth - obj.offsetWidth } if(T < 0){ T = 0; }else if(T > document.documentElement.clientHeight - obj.offsetHeight){ T = document.documentElement.clientHeight - obj.offsetHeight } obj.style.left = L + "px"; obj.style.top = T + "px"; } document.onmouseup = function(){ document.onmousemove=document.onmouseup=null; if(obj.releaseCapture){ obj.releaseCapture(); } } return false; } } } </script> </head> <body> <div id="div1"></div> <img src="img/1.jpg" id="img1" /> </body> </html>