1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 #div1{width: 200px; height: 200px;background: red;position: absolute;} 8 #div2{width: 200px; height: 200px;background: green;position: absolute;} 9 </style> 10 <script src="Drag.js"></script> 11 <script src="LimitDrag.js"></script> 12 <script> 13 window.onload=function(){ 14 new Drag('div1'); 15 new LimitDrag('div2'); 16 } 17 </script> 18 </head> 19 <body> 20 <div id="div1"> 21 普通拖拽 22 </div> 23 <div id="div2"> 24 限制范围 25 </div> 26 </body> 27 </html>
1 function Drag(id) { 2 var _this=this; 3 this.disX=0; 4 this.disY=0; 5 6 this.oDiv=document.getElementById(id); 7 this.oDiv.onmousedown=function (ev) { 8 _this.fnDown(ev); 9 10 return false; 11 } 12 } 13 14 Drag.prototype.fnDown=function (ev) { 15 var _this=this; 16 var oEvent=ev||event; 17 18 this.disX=oEvent.clientX-this.oDiv.offsetLeft; 19 this.disY=oEvent.clientY-this.oDiv.offsetTop; 20 21 document.onmousemove=function(ev){ 22 _this.fnMove(ev); 23 } 24 document.onmouseup=function () { 25 _this.fnUp(); 26 } 27 } 28 29 Drag.prototype.fnMove=function (ev) { 30 var oEvent=ev||event; 31 32 this.oDiv.style.left=oEvent.clientX-this.disX+'px'; 33 this.oDiv.style.top=oEvent.clientY-this.disY+'px'; 34 } 35 36 Drag.prototype.fnUp=function () { 37 document.onmousemove=null; 38 document.onmouseup=null; 39 }
1 function LimitDrag(id) { 2 Drag.call(this,id); //继承属性 3 } 4 5 for(var i in Drag.prototype) 6 { 7 LimitDrag.prototype[i]=Drag.prototype[i]; // 继承方法 8 } 9 10 LimitDrag.prototype.fnMove=function (ev) { 11 var oEvent=ev||event; 12 var l=oEvent.clientX-this.disX; 13 var t=oEvent.clientY-this.disY; 14 15 if(l<0) 16 { 17 l=0; 18 } 19 else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth) 20 { 21 l=document.documentElement.clientWidth-this.oDiv.offsetWidth; 22 } 23 24 this.oDiv.style.left=l+'px'; 25 this.oDiv.style.top=t+'px'; 26 }