-
Notifications
You must be signed in to change notification settings - Fork 0
/
element-drag-dragregion.html
78 lines (74 loc) · 2.46 KB
/
element-drag-dragregion.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Drag Element</title>
<style>
.dragable {
background-color: blue;
color: white;
display: inline-block;
width: 200px;
padding: 5px;
text-align: center;
}
.dragable .dragregion {
cursor: move;
display: inline-block;
background-color: aqua;
width: 30px;
border: 1px solid;
}
</style>
</head>
<body>
<div class="dragable">
<div class="dragregion">+</div>
Dragable
</div>
<script type="text/javascript">
var draggingEl = null;
var isDraggingStarted = false;
var draggingStartX = null;
var draggingStartY = null;
function dragMoveEventHandler(e) {
console.log("move");
if (!isDraggingStarted) {
isDraggingStarted = true;
}
draggingEl.style.position = "absolute";
draggingEl.style.left = `${e.pageX - draggingStartX}px`;
draggingEl.style.top = `${e.pageY - draggingStartY}px`;
}
function dragUpEventHandler(e) {
console.log("end darg");
isDraggingStarted = false;
document.removeEventListener("mousemove", dragMoveEventHandler);
document.removeEventListener("mouseup", dragUpEventHandler);
}
function dragDownEventHandeler(e) {
console.log("start drag");
draggingEl = e.target.closest(".dragable");
// Calculate the mouse position
const rect = draggingEl.getBoundingClientRect();
draggingStartX = e.pageX - rect.left;
draggingStartY = e.pageY - rect.top;
// Attach the listeners to `document`
document.addEventListener("mousemove", dragMoveEventHandler);
document.addEventListener("mouseup", dragUpEventHandler);
}
dragable_list = document.getElementsByClassName("dragable");
Array.prototype.forEach.call(dragable_list, function (el, index) {
console.log("register dragable", index);
Array.prototype.forEach.call(
el.getElementsByClassName("dragregion"),
function (el, index) {
el.addEventListener("mousedown", dragDownEventHandeler);
}
);
});
</script>
</body>
</html>