drag拖拽
# drag拖拽
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖拽</title>
<style type="text/css">
#box {
position: fixed;
left: 100px;
top: 100px;
padding: 5px;
background: #f0f3f9;
font-size: 12px;
}
#main {
border: 1px solid #a0b3d6;
background: white;
}
#bar {
line-height: 24px;
background: #beceeb;
border-bottom: 1px solid #a0b3d6;
padding-left: 5px;
cursor: move;
}
#content {
width: 420px;
height: 250px;
padding: 10px 5px;
}
</style>
</head>
<body>
<div id="box" draggable="true">
<div id="main">
<div id="bar">拖拽</div>
<div id="content">
内容……
</div>
</div>
</div>
<script type="text/javascript">
const box = document.getElementById('box')
// 开始拖拽时鼠标跟拖拽元素位置的相差值
let offset = {
x: 0,
y: 0
}
box.addEventListener("dragstart", function(event) {
// 计算偏差s
const rect = event.target.getBoundingClientRect()
offset.x = event.clientX - rect.left
offset.y = event.clientY - rect.top
// 隐藏拖拽元素,必须异步处理
setTimeout(() => {
event.target.style.display = 'none'
})
}, false);
box.addEventListener("dragend", function(event) {
// 拖拽完成,显示
event.target.style.display = 'block'
}, false);
// drop 的目标上触发
document.addEventListener("dragover", function(event) {
// 阻止默认行为以允许 drop
event.preventDefault();
}, false);
document.addEventListener("drop", function(event) {
// 阻止默认行为 (某些元素会作为链接打开)
event.preventDefault();
// 移动到鼠标的位置
box.style.left = event.clientX - offset.x + 'px'
box.style.top = event.clientY - offset.y + 'px'
}, false);
</script>
</body>
</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
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
编辑 (opens new window)