-
Notifications
You must be signed in to change notification settings - Fork 0
/
drag.html
94 lines (79 loc) · 2.34 KB
/
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>拖拽</title>
<style type="text/css">
html,
body {
margin: 0;
padding: 0;
overflow: hidden;
}
body {
color: #fff;
background: #000;
font: 12px/2 Arial;
height: 5000px;
}
#box {
position: absolute;
width: 300px;
height: 150px;
background: #333;
border: 2px solid #ccc;
top: 50%;
left: 50%;
/* transform: translate(-50%,-50%) */
margin: -75px 0 0 -150px;
}
#box h2 {
margin: 0;
padding: 0;
height: 25px;
cursor: move;
background: #222;
border-bottom: 2px solid #ccc;
text-align: left;
padding: 0 10px;
line-height: 25px;
}
</style>
</head>
<body>
<div id="box">
<h2>Drag</h2>
</div>
</body>
<script type="text/javascript">
window.onload = function () {
let title = document.querySelector('h2')
let box = document.getElementById('box')
title.onmousedown = function (event) {
let pageX = event.clientX
let pageY = event.clientY
let disX = pageX - box.offsetLeft
let disY = pageY - box.offsetTop
document.onmousemove = function (event) {
let left = event.clientX - disX
let top = event.clientY - disY
let maxLeft = window.innerWidth - box.offsetWidth
let maxTop = window.innerHeight - box.offsetHeight
// 边界处理
left = left >= maxLeft ? maxLeft : left
top = top >= maxTop ? maxTop : top
left = left <= 0 ? 0 : left
top = top <= 0 ? 0 : top
box.style.marginLeft = 0;
box.style.marginTop = 0;
box.style.left = left + 'px'
box.style.top = top + 'px'
}
}
document.onmouseup = function () {
// title.onmousedown = null
document.onmousemove = null
}
}
</script>
</html>