Drag.js
function Drag(id) { var _this = this; this.disX = 0; this.disY = 0; this.oDiv = document.getElementById(id); this.oDiv.onmousedown = function (ev) { _this.fnDown(ev); }; } Drag.prototype.fnDown = function(ev) { var _this = this; var oEvent = ev||event; //鼠标距离减去物体位置 this.disX = oEvent.clientX-this.oDiv.offsetLeft; this.disY = oEvent.clientY-this.oDiv.offsetTop; document.onmousemove = function (ev) { _this.fnMove(ev); }; document.onmouseup = function () { _this.fnUp(); }; }; Drag.prototype.fnMove = function(ev) {//限制范围添加到这里 var oEvent = ev||event; this.oDiv.style.left = oEvent.clientX-this.disX+'px'; this.oDiv.style.top = oEvent.clientY-this.disY+'px'; }; Drag.prototype.fnUp =function() { document.onmousemove = null; document.onmouseup = null; }
LimitDrag.js
function LimitDrag(id) { //用构造函数伪装,继承属性 Drag.call(this,id); } //用原型链继承方法 for(var i in Drag.prototype){ LimitDrag.prototype[i] = Drag.prototype[i]; } LimitDrag.prototype.fnMove = function (ev) {//覆盖Drag.js里的方法。 var oEvent = ev||event; var l = oEvent.clientX-this.disX; var t = oEvent.clientY-this.disY; if(l<0){ l=0; }else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){ l=document.documentElement.clientWidth-this.oDiv.offsetWidth; } if(t<0){ t=0; }else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight){ t=document.documentElement.clientHeight-this.oDiv.offsetHeight; } this.oDiv.style.left =l +'px'; this.oDiv.style.top = t+'px'; }
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> #div1{width:100px;height:100px;background-color:green;position:absolute;left:0;top:0;} #div2{width:100px;height:100px;background-color:red;position:absolute;right:0;top:0;} </style> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html> <script type="text/javascript" src="Drag.js"></script> <script type="text/javascript" src="LimitDrag.js"></script> <script type="text/javascript"> window.onload = function () { new Drag("div1"); new LimitDrag("div2"); } </script>