您的位置:首页 > 其它

拷贝继承实现拖拽

2017-06-12 01:12 169 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>继承的拖拽</title>
<!--

div1:表示最普通的拖拽,用它来充当父类,
div2 :也是拖拽,用它来充当子类,但是它的拖拽有一定的限制范围,不能超出可视区域
然后我们就通过拷贝继承来实现拖拽,并实现他们不一样的地方
-->
<style>
#div1{width: 100px;height: 100px;background: red;position: absolute;cursor: pointer;}
#div2{width: 100px;height: 100px;background: yellow;position: absolute;left: 100px;cursor: pointer;}
</style>
</head>
<body>
<div id = 'div1'></div>
<div id = 'div2'></div>
<script>
window.onload = function(){
var d1 = new Drag('div1');
d1.init();
var d2 = new childDrag('div2');
d2.init();
};

function Drag(id){    // 父类
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}

Drag.prototype.init = function(){
var This = this;
this.obj.onmousedown = function(ev){
var ev = ev || window.event;
This.fnDown(ev);

document.onmousemove = function(ev){
var ev = ev || window.event;
This.fnMove(ev);
};

document.on,onmouseup = function(){
This.fnUp();
};

// 阻止默认事件
return false;
};
};

Drag.prototype.fnDown = function(ev){
this.disX = ev.clientX - this.obj.offsetLeft;
this.disY = ev.clientY - this.obj.offsetTop;
};

Drag.prototype.fnMove =function(ev){
this.obj.style.left = ev.clientX - this.disX + 'px';
this.obj.style.top = ev.clientY - this.disY + 'px';
};

Drag.prototype.fnUp = function(){
document.onmousemove = null;
document.onmouseup = null;
};

function childDrag(id){    //子类
// 继承父类属性
Drag.call(this,id);
}

// 实现继承父类方法
extend(childDrag.prototype,Drag.prototype);

//封装方法 通过for in 实现拷贝继承 父类方法
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}

// 重写子类的fnMove方法 限制子类拖拽范围在可视区域
childDrag.prototype.fnMove =function(ev){
var L = ev.clientX - this.disX;
var T = ev.clientY - this.disY;
if(L < 0){
L = 0;
}else if(L > document.documentElement.clientWidth - this.obj.offsetWidth){
L = document.documentElement.clientWidth - this.obj.offsetWidth;
}

if(T < 0){
T = 0;
}else if(T > document.documentElement.clientHeight - this.obj.offsetHeight){
T = document.documentElement.clientHeight - this.obj.offsetHeight;
}
this.obj.style.left = L + 'px';
this.obj.style.top = T + 'px';
};
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息