javascript面向对象系列第五篇

时间:2023-09-06 09:02:20
javascript面向对象系列第五篇
<style>
.test{height: 50px;width: 50px;background-color: pink;position:absolute;}
#test2{left:60px;background-color: lightblue;}
</style>
</head>
<body>
<div id="test1" class="test"></div>
<div id="test2" class="test"></div>
<script>
function Drag(obj){
this.obj= obj;
}
Drag.prototype.init = function(){
var that = this;
this.obj.onmousedown = function(e){
e = e || event;
that.fnDown(e);
document.onmousemove = function(e){
e = e || event;
that.fnMove(e);
}
document.onmouseup = function(){
that.fnUp();
}
return false;
}
};
Drag.prototype.fnDown = function(e){
this.disX = e.clientX - this.obj.offsetLeft;
this.disY = e.clientY - this.obj.offsetTop;
}
Drag.prototype.fnMove = function(e){
this.obj.style.left = e.clientX - this.disX + 'px';
this.obj.style.top = e.clientY - this.disY + 'px';
}
Drag.prototype.fnUp = function(){
document.onmousemove = document.onmouseup = null;
}
function ChildDrag(obj){
Drag.call(this,obj);
}
if(!Object.create){
  Object.create = function(proto){
    function F(){};
    F.prototype = proto;
    return new F;
  }
}
ChildDrag.prototype = Object.create(Drag.prototype);
ChildDrag.prototype.constructor = ChildDrag;
var drag1 = new Drag(test1);
drag1.init();
ChildDrag.prototype.fnMove = function(e){
var L = e.clientX - this.disX;
var T = e.clientY - this.disY;
if(L < 0){L = 0;}
if(T < 0){T = 0;}
this.obj.style.left = L + 'px';
this.obj.style.top = T + 'px';
}
var drag2 = new ChildDrag(test2);
drag2.init();
</script>
javascript面向对象系列第五篇