Skip to content

Commit b7388f8

Browse files
authored
Create 面向对象 拖拽.html
1 parent 595d357 commit b7388f8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

面向对象 拖拽.html

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

0 commit comments

Comments
 (0)