-
Notifications
You must be signed in to change notification settings - Fork 27.3k
/
Copy pathmulti-control-box-drag.html
101 lines (82 loc) · 2.32 KB
/
multi-control-box-drag.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
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
<title>Multi control box drag example</title>
<style>
html {
font-family: sans-serif;
overflow: hidden;
}
body {
background: #ffe;
margin: 0;
}
div {
background-color: #1FE200;
background-image: linear-gradient(to bottom right, rgba(0,0,0,0), rgba(0,0,0,0.4));
width: 200px;
height: 150px;
border: 1px solid green;
position: absolute;
}
</style>
</head>
<body>
<div></div>
<script>
document.body.width = window.innerWidth;
document.body.height = window.innerHeight;
let posX, posY;
document.onmousemove = positionHandler;
document.ontouchmove = positionHandler;
function positionHandler(e) {
if ((e.clientX)&&(e.clientY)) {
posX = e.clientX;
posY = e.clientY;
} else if (e.targetTouches) {
posX = e.targetTouches[0].clientX;
posY = e.targetTouches[0].clientY;
e.preventDefault();
}
}
const div = document.querySelector('div');
let initialPosX = null;
let initialPosY = null;
let rAF;
div.onmousedown = function() {
initialBoxX = div.offsetLeft;
initialBoxY = div.offsetTop;
movePanel();
}
div.ontouchstart = function(e) {
initialBoxX = div.offsetLeft;
initialBoxY = div.offsetTop;
positionHandler(e);
movePanel();
}
document.onmouseup = stopMove;
document.ontouchend = stopMove;
function movePanel() {
if(initialPosX === null) {
initialPosX = posX;
initialPosY = posY;
} else {
let posMoveX = posX - initialPosX;
let posMoveY = posY - initialPosY;
let offsetX = initialBoxX + posMoveX;
let offsetY = initialBoxY + posMoveY;
div.style.left = offsetX + 'px';
div.style.top = offsetY + 'px';
}
rAF = requestAnimationFrame(movePanel);
}
function stopMove() {
cancelAnimationFrame(rAF);
initialPosX = null;
initialPosY = null;
}
</script>
</body>
</html>