window.onload = function () { new Drag("div1"); new LimiteDrag("div12"); }; /////////////正常的没有限制范围的Drag函数//////////////////// function Drag(id) { this.oDiv = document.getElementById(id); this.disX = 0; this.disY = 0; var _this = this; this.oDiv.onmousedown = function(){ _this.fnDown(); }; }; Drag.prototype.fnDown = function(ev) { var ev = ev || window.event; var _this = this; this.disX = ev.clientX - this.oDiv.offsetLeft; this.disY = ev.clientY - this.oDiv.offsetTop; document.onmousemove = function(){ _this.fnMove(); }; document.onmouseup = function(){ _this.fnUp(); }; }; Drag.prototype.fnMove = function(ev) { var ev = ev || window.event; this.oDiv.style.left = ev.clientX - this.disX + "px"; this.oDiv.style.top = ev.clientY - this.disY + "px"; }; Drag.prototype.fnUp = function() { document.onmousemove = document.onmouseup = null; }; /////////继承Drag对象,并添加限制范围的方法,变成新的LimiteDrag函数/////////// function LimiteDrag(id) { Drag.call(this,id); // 第一步:执行Drag函数,通过Call(this)来改变this指向 }; for(var i in Drag.prototype){ // 第二步:浅拷贝,拷贝Drag上面所有的原型方法 LimiteDrag.prototype[i] = Drag.prototype[i]; }; LimiteDrag.prototype.fnMove = function(ev) { // 第三步:覆盖并改变从Drag上面拷贝过来的fnMove方法 var ev = ev || window.event; var l = ev.clientX - this.disX; var t = ev.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"; };
面向对象的继承与修改(拖拽实例)
最新推荐文章于 2020-01-29 16:33:19 发布