用自定义事件的方法实现拖拽组件的开发

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
<script>
window.onload = function () {
var d1 = new Drag();
d1.init({
id: "div1"
});
var d2 = new Drag();
d2.init({
id: "div2"
});
bindEvent(d2, "toDown", function () {
document.getElementById("div2").style.backgroundColor = "yellow"
});
var d3 = new Drag();
d3.init({
id: "div3"
});
bindEvent(d3, "toDown", function () {
document.getElementById("div3").style.backgroundColor = "yellowgreen"
});
bindEvent(d3, "toUp", function () {
document.getElementById("div3").style.backgroundColor = "purple"
});
var d4 = new Drag();
d4.init({
id: "div4"
});
bindEvent(d4, "toUp", function () {
alert("byebye")
})
};
function Drag() {
this.obj = null;
this.deltaX = 0;
this.deltaY = 0;
this.settings = {}
}
Drag.prototype.init = function (opt) {
var This = this;
this.obj = document.getElementById(opt.id);
extend(this.settings, opt);
this.obj.onmousedown = function (ev) {
var ev = ev || window.event;
This.fnDown(ev);
fireEvent(This, "toDown");
document.onmousemove = function (ev) {
var ev = ev || window.event;
This.fnMove(ev);
return false;
};
document.onmouseup = function () {
This.fnUp();
fireEvent(This, "toUp");
};
return false;
}
};
Drag.prototype.fnDown = function (ev) {
this.deltaX = ev.clientX - this.obj.offsetLeft;
this.deltaY = ev.clientY - this.obj.offsetTop;
};
Drag.prototype.fnMove = function (ev) {
this.obj.style.left = ev.clientX - this.deltaX + "px";
this.obj.style.top = ev.clientY - this.deltaY + "px";
};
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
function bindEvent(obj, events, fn) {
obj.listeners = obj.listeners || {};
obj.listeners[events] = obj.listeners[events] || [];
obj.listeners[events].push(fn);
if (obj.nodeType) {
if (obj.addEventListener) {
obj.addEventListener(events, fn, false);
} else {
obj.attachEvent("on" + events, fn);
}
}
}
function fireEvent(obj, events) {
if (obj.listeners && obj.listeners[events]) {
for (var i = 0; i < obj.listeners[events].length; i++) {
obj.listeners[events][i]();
}
}
}
function extend(obj1, obj2) {
for (var attr in obj2) {
obj1[attr] = obj2[attr];
}
}
</script>

本文结束,感谢阅读。

本文作者:melody0z
本文链接:https://melodyvoid/JavaScript/implementation-of-drag-and-drop-components-using-custom-events.html
欢迎转载,转载请注明文本链接

坚持原创技术分享,您的支持将鼓励我继续创作!