-
Notifications
You must be signed in to change notification settings - Fork 0
/
drag.js
77 lines (67 loc) · 1.51 KB
/
drag.js
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
window.onload=function(){
var d1=new Drag("div1");
d1.init();
var d2=new ChildDrag("div2");
d2.init();
console.log(ChildDrag.prototype);
}
function Drag(id){
this.obj=document.getElementById(id);
this.disX=0;
this.disY=0;
}
Drag.prototype={
constructor: Drag,
init: function(){
var This=this;
this.obj.onmousedown=function(ev){
var ev=ev||window.event;
This.fnDown(ev);
document.onmousemove=function(ev){
var ev=ev||window.event;
This.fnMove(ev);
};
document.onmouseup=function(){
This.fnUp();
};
return false;
}
},
fnDown: function(ev){
this.disX=ev.clientX-this.obj.offsetLeft;
this.disY=ev.clientY-this.obj.offsetTop;
},
fnMove: function(ev){
this.obj.style.left=ev.clientX-this.disX+'px';
this.obj.style.top=ev.clientY-this.disY+'px';
},
fnUp: function(){
document.onmousemove=null;
document.onmouseup=null;
}
}
extend(ChildDrag.prototype,Drag.prototype);
function ChildDrag(id){
Drag.call(this,id);
}
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr]=obj2[attr];
}
}
ChildDrag.prototype.fnMove=function(ev){
var l=ev.clientX-this.disX;
var t=ev.clientY-this.disY;
if(l<0){
l=0;
}else if(l>document.documentElement.clientWidth-this.obj.offsetWidth){
l=document.documentElement.clientWidth-this.obj.offsetWidth;
}
if(t<0){
t=0;
}else if(t>document.documentElement.clientHeight-this.obj.offsetHeight){
t=document.documentElement.clientHeight-this.obj.offsetHeight;
}
this.obj.style.left=l+'px';
this.obj.style.top=t+'px';
}