拖拽类
xianghaifeng 2024-06-25 js 基础
# class 实现
/**
* @class Dragger 拖拽类
* @function init() 初始化
* @function initDrag() 初始化拖拽
* @function move() 拖拽中
* @function up() 拖拽结束
*/
class Dragger {
constructor(el) {
this.el = el;
this.mouse = {};
this.mouse.init = false;
this.init();
this.initDrag();
}
init() {
this.el.style.position = "absolute";
this.el.style.top = `${this.el.offsetTop}px`;
this.el.style.left = `${this.el.offsetLeft}px`;
}
initDrag() {
this.el.addEventListener("mousedown", (e) => {
if (/input|textarea/.test(e.target.tagName.toLowerCase())) return false;
this.mouse.init = true;
this.mouse.offsetX = e.pageX - this.el.offsetLeft;
this.mouse.offsetY = e.pageY - this.el.offsetTop;
this.moveHandler = this.move.bind(this);
this.upHandler = this.up.bind(this);
window.addEventListener("mousedown", this.moveHandler);
window.addEventListener("mouseup", this.upHandler);
});
}
move(e) {
console.log(e);
if (!this.mouse.init) return false;
this.el.style.left = e.pageX - this.mouse.offsetX + "px";
this.el.style.top = e.pageY - this.mouse.offsetY + "px";
}
up() {
this.mouse.init = false;
console.log("ok");
window.removeEventListener("mousedown", this.moveHandler);
window.removeEventListener("mouseup", this.upHandler);
}
}
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
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