首页 > 代码库 > 继承案例_限制范围的拖拽
继承案例_限制范围的拖拽
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>
继承案例_限制范围的拖拽
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。