您的位置:首页 > 其它

面向对象的继承与修改(拖拽实例)

2017-05-26 15:58 197 查看
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";
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面向对象 继承