-
Notifications
You must be signed in to change notification settings - Fork 0
/
drag-and-drop.html
43 lines (37 loc) · 973 Bytes
/
drag-and-drop.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
<!doctype html>
<style>
html,
body {
margin: 0;
padding: 0;
height: 100%;
}
#draggable {
cursor: pointer;
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
background: black;
}
</style>
<div id="draggable"></div>
<script>
const draggable = document.getElementById('draggable');
draggable.addEventListener('mousedown', event => onMouseDown(draggable, event));
const onMouseDown = (el, event) => {
const deltaX = event.clientX - el.offsetLeft;
const deltaY = event.clientY - el.offsetTop;
const onMouseMove = (event) => {
el.style.left = (event.clientX - deltaX) + 'px';
el.style.top = (event.clientY - deltaY) + 'px';
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove, true);
document.removeEventListener('mouseup', onMouseUp, true);
};
document.addEventListener('mousemove', onMouseMove, true);
document.addEventListener('mouseup', onMouseUp, true);
};
</script>