<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#box1{
width: 100px;
height: 100px;
background-color: #ffff00;
position: absolute;
}
#box2{
width: 100px;
height: 100px;
background-color: #0000ff;
position: absolute;
left: 120px;
}
</style>
<script>
window.οnlοad=function(){
new Drag("box1")
new Drag("box2")
}
//第四步:全局变量变成属性 该加this加this
// var oDiv=null;
// var disX=0;
// var disY=0;
//第三步:Window.onload改成构造函数
function Drag(id){
this.disX=0
this.disY=0
var _this=this;
this.oDiv=document.getElementById(id);
this.oDiv.οnmοusedοwn=function(){
//第六步 修改当前的从属关系
_this.fnDown()
};
}
//第五步:把函数改为Drag原型方法
Drag.prototype.fnDown=function(ev){
var _this=this;
var oEvent=ev||event;
this.disX = oEvent.clientX-this.oDiv.offsetLeft;
this.disY = oEvent.clientY-this.oDiv.offsetTop;
document.οnmοusemοve=function(){
_this.fnMove()
}
document.οnmοuseup=function(){
_this.fnUp()
}
}
Drag.prototype.fnMove=function(ev){
var oEvent=ev||event;
this.oDiv.style.left=oEvent.clientX-this.disX+'px';
this.oDiv.style.top=oEvent.clientY-this.disY+'px';
}
Drag.prototype.fnUp=function(){
document.οnmοusemοve=null;
document.οnmοuseup=null;
}
</script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>