-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrag-and-drop-test1.html
108 lines (93 loc) · 2.68 KB
/
drag-and-drop-test1.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and Drop</title>
<style>
* {
box-sizing: border-box;
}
.container {
display: flex;
justify-content: space-between;
margin: 2ch;
}
.dropzone {
width: calc(50% - 1ch);
padding: 2ch;
border: 1px solid gray;
}
.draggable {
border: 1px solid lightgray;
padding: 1.5ch;
background-color: #efefef;
cursor: move;
}
.draggable + .draggable {
margin-top: 1.5ch;
}
.draggable.is-dragging {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="container">
<section class="dropzone source">
<div class="draggable" id="drag-1" draggable="true">drag-1</div>
<div class="draggable" id="drag-2" draggable="true">drag-2</div>
<div class="draggable" id="drag-3" draggable="true">drag-3</div>
<div class="draggable" id="drag-4" draggable="true">drag-4</div>
<div class="draggable" id="drag-5" draggable="true">drag-5</div>
</section>
<section class="dropzone target">
</section>
</div>
<script>
const dropzoneSource = document.querySelector(".source");
const dropzone = document.querySelector(".target");
const dropzones = [...document.querySelectorAll(".dropzone")];
const draggables = [...document.querySelectorAll(".draggable")];
function getDragAfterElement(container, y) {
const draggableElements = [
...container.querySelectorAll(".draggable:not(.is-dragging)")
];
return draggableElements.reduce(
(closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
if (offset < 0 && offset > closest.offset) {
return {
offset,
element: child
};
} else {
return closest;
}
},
{ offset: Number.NEGATIVE_INFINITY }
).element;
}
draggables.forEach((draggable) => {
draggable.addEventListener("dragstart", (e) => {
draggable.classList.add("is-dragging");
});
draggable.addEventListener("dragend", (e) => {
draggable.classList.remove("is-dragging");
});
});
dropzones.forEach((zone) => {
zone.addEventListener("dragover", (e) => {
e.preventDefault();
const afterElement = getDragAfterElement(zone, e.clientY);
const draggable = document.querySelector(".is-dragging");
if (afterElement === null) {
zone.appendChild(draggable);
} else {
zone.insertBefore(draggable, afterElement);
}
});
});
</script>
</body>
</html>