用面向对象写一个拖拽,并实现继承
思路:先用面过过程的方法将要实现的效果实现出来,然后按照以下步骤将拆分成面向对象
//面向过程的程序改写成面向对象程序不能有函数嵌套
//将window.onload初始化整个程序改为构造函数初始化整个对象
//将面向过程中的变量改为属性
//将面向过程中的函数改为方法
index.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>面向对象拖拽</title>
<style>
#div1{width: 200px;height: 200px;background: red;position: absolute;}
#div2{width: 200px;height: 200px;background: green;position: absolute;}
</style>
<script src="drag.js"></script>
<script src="limitDrag.js"></script>
<script>
window.onload = function(){
new Drag("div1");
new limitDrag("div2");
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
Drag.js文件
function Drag(id){
this.disX = 0;
this.disY = 0;
var _this = this;
this.oDiv = document.getElementById(id);
this.oDiv.onmousedown = function(e){
_this.fnDown(e);
return false;
};
}
Drag.prototype.fnDown = function(e){
var _this = this;
var e = e || window.event;
this.disX = e.clientX-this.oDiv.offsetLeft;
this.disY = e.clientY-this.oDiv.offsetTop;
document.onmousemove = function(e){
_this.fnMove(e);
};
document.onmouseup = function(){
_this.fnUp();
};
}
Drag.prototype.fnMove = function(e){
var e = e || window.event;
this.oDiv.style.left = e.clientX-this.disX + 'px';
this.oDiv.style.top = e.clientY-this.disY + 'px';
}
Drag.prototype.fnUp = function(e){
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(e){
var e = e || window.event;
var l = e.clientX-this.disX;
var t = e.clientY-this.disY;
if(l<0){
l=0;
}else if(l>document.documentElement.clientWidth - this.oDiv.offsetWidth){
l=document.documentElement.clientWidth - this.oDiv.offsetWidth
}
this.oDiv.style.left = l + 'px';
this.oDiv.style.top = t + 'px';
}