拖拽组件的开发

先要搞懂配置参数和默认参数

有配置参数,走配置参数,没有配置参数走默认参数。(前提是属性的名字必须一样,这样配置参数才会覆盖默认参数)

先来看一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
var a = { //配置参数
name:"Jack"
};
var b = { //默认参数
name: "Mary"
};
extend(b,a);
console.log(b.name); //"Jack" 如果有配置参数,就走配置参数
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
var a = { //配置参数
//name:"Jack"
};
var b = { //默认参数
name: "Mary"
};
extend(b,a);
console.log(b.name); //"Mary" 如果没有配置参数,就走默认参数
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}
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
//组件开发:多组对象,像兄弟之间的关系(代码复用)
window.onload = function () {
var d1 = new Drag();
d1.init({ //配置参数
id:"div1"
});
var d2 = new Drag();
d2.init({
id:"div2",
toDown: function () {
document.getElementById("div2").style.backgroundColor = "yellow"
}
});
var d3 = new Drag();
d3.init({
id:"div3",
toDown: function () {
document.getElementById("div3").style.backgroundColor = "yellowgreen"
},
toUp : function () {
document.getElementById("div3").style.backgroundColor = "purple"
}
});
var d4 = new Drag();
d4.init({
id:"div4",
toUp: function () {
alert("byebye")
}
})
};
function Drag(){
this.obj = null;
this.deltaX = 0;
this.deltaY = 0;
//默认参数
this.settings = {
toDown : function (){},
toUp : function () {}
}
}
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);
This.settings.toDown();
document.onmousemove = function (ev) {
var ev = ev || window.event;
This.fnMove(ev);
return false;
};
document.onmouseup = function () {
This.fnUp();
This.settings.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) {
var l = ev.clientX - this.deltaX;
var t = ev.clientY - this.deltaY;
this.obj.style.left = l + "px";
this.obj.style.top = t + "px";
};
Drag.prototype.fnUp = function () {
document.onmousemove = null;
document.onmouseup = null;
};
function extend(obj1,obj2){
for(var attr in obj2){
obj1[attr] = obj2[attr];
}
}

本文结束,感谢阅读。

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

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