js面向对象编程以及继承

时间:2023-01-05 17:21:59
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js</title>
<style>
#div1{
width: 200px;
height:300px;
background-color: #2aabd2;
position: absolute;
}

#div2{
width: 100px;
height:200px;
background-color: #d28544;
position: absolute;
}

</style>
</head>
<body>
<div id="div1">原来的</div>
<div id="div2">继承的</div>
</body>
<script>

//面向过程代码
// function move1(){
// var oDiv=document.getElementById('div1');
// var disX=0;
// var disY=0;
// oDiv.onmousedown=function(ev){
// var oEvent=ev||event;
// disX=oEvent.clientX-oDiv.offsetLeft;
// disY=oEvent.clientY-oDiv.offsetTop;
//
// document.onmousemove=function(ev){
// var oEvent=ev||event;
// oDiv.style.left=oEvent.clientX-disX+'px';
// oDiv.style.top=oEvent.clientY-disY+'px';
// };
// document.onmouseup= function () {
// document.onmousemove=null;
// document.onmouseup=null;
// }
// }
// }
//改写为面向对象
window.onload=function(){
new move1('div1');
new limitMove('div2');
};
function move1(id){
var _this=this;
this.oDiv=document.getElementById(id);
this.disX=0;
this.disY=0;
this.oDiv.onmousedown=function(ev){
_this.down(ev);
return false;
}
}
move1.prototype.down=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.move(ev);
};
document.onmouseup=function(){
_this.up();
}
};
move1.prototype.move=function (ev){
var oEvent=ev||event;
this.oDiv.style.left=oEvent.clientX-this.disX+'px';
this.oDiv.style.top=oEvent.clientY-this.disY+'px';
};
move1.prototype.up=function () {
document.onmousemove=null;
document.onmouseup=null;
};
//继承以上方法

function limitMove(id){
move1.call(this,id); //继承属性
}
for(var i in move1.prototype){
limitMove.prototype[i]=move1.prototype[i]; //继承方法
}
limitMove.prototype.move=function(ev){ //重写move方法,限制移动范围
var oEvent=ev||event;
var x=oEvent.clientX-this.disX;
var y=oEvent.clientY-this.disY;
if(x<50){
x=0;
}
else if(x>document.documentElement.offsetWidth-this.oDiv.offsetWidth){
x=document.documentElement.offsetWidth-this.oDiv.offsetWidth;
}
if(y<50){ //产生磁力吸附效果
y=0;
}
else if(y>document.documentElement.clientHeight-this.oDiv.offsetHeight){
y=document.documentElement.clientHeight-this.oDiv.offsetHeight;
}
this.oDiv.style.left=x+'px';
this.oDiv.style.top=y+'px';
}
</script>
</html>