-
Notifications
You must be signed in to change notification settings - Fork 0
/
toDrag.html
124 lines (120 loc) · 2.54 KB
/
toDrag.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>拖拽框</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.div1{
position: fixed;
width: 50%;
top: 10%;
left: 25%;
background-color: #fff;
box-shadow: 3px 3px 5px #aaa;
}
.div2{
padding: 20px 10px;
background-color: #23f;
color: #fff;
cursor: move;
font-weight: bold;
}
</style>
</head>
<body>
<div class="div1">
<div class="div2">
开始拖动
</div>
<div>让我一起走吧</div>
<div>那就一起走吧</div>
<div>肯定一起走啊</div>
<div>一定一起走啊</div>
</div>
<script type="text/javascript">
window.onload=function(){
toDragBox("div2");
}
// 拖拽
function toDragBox(eleClass){
// 超出边界值
var mx=50;
var my=50;
var a=this;
var aDiv=getByClass(document,eleClass);
for(var i=0, len=aDiv.length;i<len;i++){
aDiv[i].onmousedown=function(ev){
var oDiv=this.parentNode;
var oEvent=ev||event;
var x=oEvent.clientX-oDiv.offsetLeft;
var y=oEvent.clientY-oDiv.offsetTop;
if(oDiv.setCapture){
oDiv.onmousemove=function(ev){
a.mosueMove(ev,oDiv,x,y);
}
oDiv.onmouseup=function(ev){
a.mouseUp(oDiv);
}
oDiv.setCapture();
}
else{
document.onmousemove=function(ev){
a.mosueMove(ev,oDiv,x,y);
}
document.onmouseup=function(ev){
a.mouseUp(document);
}
}
return false;
}
}
a.mosueMove=function(ev,obj,x,y){
var oEvent=ev||event;
var oX=oEvent.clientX-x;
var oY=oEvent.clientY-y;
if(oX<-mx){
oX=-mx;
}
if(oX>document.documentElement.offsetWidth-obj.offsetWidth/2){
oX=document.documentElement.offsetWidth-obj.offsetWidth/2;
}
if(oY<-my){
oY=-my;
}
if(oY>document.documentElement.clientHeight-obj.offsetHeight/2){
oY=document.documentElement.clientHeight-obj.offsetHeight/2;
}
obj.style.left=oX+"px";
obj.style.top=oY+"px";
};
a.mouseUp=function(obj){
obj.onmousemove=null;
obj.onmouseup=null;
if(obj.releaseCapture){
obj.releaseCapture();
}
};
}
// 获取class
function getByClass(oParent,sClass){
var aEle=oParent.getElementsByTagName("*");
var aResult=[];
for(var i=0,tt=aEle.length;i<tt;i++){
if(aEle[i].className.indexOf(sClass)>=0){
var arr_class=aEle[i].className.split(" ");
for(var j=0,len=arr_class.length;j<len;j++){
if(arr_class[j]==sClass){
aResult.push(aEle[i]);
}
}
}
}
return aResult;
}
</script>
</body>
</html>