<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1{ width: 200px; height: 200px; position: absolute; background: red; } #div2{ width: 200px; height: 200px; position: absolute; background: green; } </style> <script src="面向对象拖拽.js"></script> <script src="限制范围拖拽(继承).js"></script> <script> window.onload=function () { new Drag('div1'); new LimitDrag('div2') } </script> </head> <body> <div id="div1">普通拖拽</div> <div id="div2">限制范围拖拽</div> </body> </html>
//普通拖拽 function Drag(id) { this.oDiv=document.getElementById(id) this.dis_x=0; this.dis_y=0; var _this=this; this.oDiv.onmousedown=function (ev) { _this.fnDown(ev) } } Drag.prototype.fnDown=function (ev) { var oEvent=ev||event; this.dis_x=oEvent.clientX-this.oDiv.offsetLeft; this.dis_y=oEvent.clientY-this.oDiv.offsetTop; var _this=this; document.onmousemove=function (ev) { _this.fnMove(ev) } document.onmouseup=function (ev) { _this.fnUp(); } } Drag.prototype.fnMove=function (ev) { var oEvent=ev||event; this.oDiv.style.left=oEvent.clientX-this.dis_x+'px'; this.oDiv.style.top=oEvent.clientY-this.dis_y+'px'; } Drag.prototype.fnUp=function () { document.onmousedown=null; document.onmousemove=null; }
//限制范围的拖拽 function LimitDrag(id) { Drag.call(this,id); } for (var i in Drag.prototype) { LimitDrag.prototype[i]=Drag.prototype[i] } LimitDrag.prototype.fnMove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-this.dis_x; var t=oEvent.clientY-this.dis_y; if (l<0) { l=0 } else if (l>document.documentElement.clientWidth-this.oDiv.offsetWidth) { l=document.documentElement.clientWidth-this.oDiv.offsetWidth } this.oDiv.style.left=l+'px'; if (t<0) { t=0 } else if (t>document.documentElement.clientHeight-this.oDiv.offsetHeight) { t=document.documentElement.clientHeight-this.oDiv.offsetHeight } this.oDiv.style.top=t+'px'; }