-
Notifications
You must be signed in to change notification settings - Fork 27.2k
/
Copy pathsimple-box-drag.html
88 lines (69 loc) · 1.93 KB
/
simple-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
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Simple 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 mouseX, mouseY;
document.onmousemove = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
const div = document.querySelector('div');
let initialMouseX = null;
let initialMouseY = null;
var initialBoxX, initialBoxY, rAF;
div.onmousedown = function() {
initialBoxX = div.offsetLeft;
initialBoxY = div.offsetTop;
movePanel();
}
document.onmouseup = stopMove;
function movePanel() {
if(initialMouseX === null) {
initialMouseX = mouseX;
initialMouseY = mouseY;
} else {
let mouseMoveX = mouseX - initialMouseX;
let mouseMoveY = mouseY - initialMouseY;
let offsetX = initialBoxX + mouseMoveX;
let offsetY = initialBoxY + mouseMoveY;
console.log(offsetX + ' ' + offsetY);
div.style.left = offsetX + 'px';
div.style.top = offsetY + 'px';
}
rAF = requestAnimationFrame(movePanel);
}
function stopMove() {
cancelAnimationFrame(rAF);
console.log('mousemove stopped');
initialMouseX = null;
initialMouseY = null;
}
</script>
</body>
</html>