实现有限的Drag拖拽
将Drag和limitDrag类实现继承和封装
Drag.js
/** * Created by Jimmy on 2016/3/7. */ function Drag(id){ var _this=this; this.disX=0;//作为属性 this.disY=0;//作为属性 this.oDiv=document.getElementById(id); // this.oDiv.οnmοusedοwn=this.fnDown; this.oDiv.οnmοusedοwn=function(ev) { _this.fnDown(ev); return false; } }; Drag.prototype.fnDown=function(ev)//将以下函数用原型修改变成一个方法 // function fnDown(ev) { var _this=this; var onEvent=ev||event; this.disX=onEvent.clientX-this.oDiv.offsetLeft; this.disY=onEvent.clientY-this.oDiv.offsetTop; // document.οnmοusemοve=this.fnMove; document.onmousemove=function(ev) { _this.fnMove(ev); }; // document.onmoseup=this.fnMoveup; document.onmouseup=function() { _this.fnMoveup(); }; }; 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.fnMoveup=function () { // alert ('拉拉啊'); document.onmousemove=null; document.onmouseup=null; };limitDrag.js
/** * Created by Jimmy on 2016/3/7. */ 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.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.clientWidth-this.oDiv.offsetTop) { t=document.documentElement.clientWidth-this.oDiv.offsetTop; } this.oDiv.style.left=l-this.disX+'px'; this.oDiv.style.top=t-this.disY+'px'; };
limitDrag.html
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> #div1{width: 200px;height: 200px;background: yellow;position: absolute;} #div2{width: 200px;height: 200px;background: green;position: absolute;} </style> <script src="Drag.js"></script> <script src="limitDrag.js"></script> </head> <body> <script> //初始化对象 window.onload=function() { new Drag('div1'); new limitDrag('div2'); }; </script> <div id="div1">普通拖拽</div> <div id="div2">限制范围</div> </body> </html>