/
面向对象 拖拽.html
77 lines (75 loc) · 1.4 KB
/
面向对象 拖拽.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!Doctype HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style>
#div{
width: 100px;
height: 100px;
background: blue;
position: absolute;
top: 100px;
left: 100px;
}
#div1{
width: 100px;
height: 100px;
background: yellow;
position: absolute;
top: 100px;
left: 100px;
}
</style>
</head>
<body>
<div id="div"></div>
<div id="div1"></div>
</body>
<script>
window.onload=function()
{
new Drag('div');
new Drag('div1');
}
function Drag(id)
{
var _this=this;
/*解决遇到事件后this指向改变的问题*/
this.disX=0;
this.disY=0;
this.oDiv= document.getElementById(id);
this.oDiv.onmousedown=function()
{
_this.fnDown();/*遇到事件this指向改变 的解决方法*/
}
}
Drag.prototype.fnDown=function(ev)
{
var _this=this;
var oEven=ev||event;
this.disX=oEven.clientX-this.oDiv.offsetLeft;
this.disY=oEven.clientY-this.oDiv.offsetTop;
document.onmousemove=function()
{
_this.fnMove();
/*遇到事件this指向改变 的解决方法*/
};
document.onmouseup=function()
{
_this.fnUp();/*遇到事件this指向改变 的解决方法*/
};
};
Drag.prototype.fnMove=function(ev)
{
var oEven=ev||event;
this.oDiv.style.left=oEven.clientX-this.disX+'px';
this.oDiv.style.top =oEven.clientY-this.disY+'px';
};
Drag.prototype.fnUp=function()
{
document.onmousemove=null;
document.onmouseup=null;
};
</script>
</html>