-
Notifications
You must be signed in to change notification settings - Fork 1
/
drag.html
83 lines (68 loc) · 2.39 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>implement drag function</title>
<style type="text/css">
#demo {
position: absolute;
width: 200px;
height: 200px;
/*left: 50%;
top: 50%;
margin: -100px 0 0 -100px;*/
left: 580px;
top: 250px;
background: #5BBF5A;
cursor: move;
}
</style>
</head>
<body>
<div id="demo"></div>
<script type="text/javascript">
var demo = document.getElementById('demo');
var isDrag = false; //标记元素是否可以拖拽
var mouseOffsetX = 0; //鼠标相对元素左上角的偏移
var mouseOffsetY = 0;
//鼠标事件1 - 当鼠标在div中按下时,计算鼠标相对拖拽元素的左上角的位置,并且标记元素为可以拖拽的
demo.addEventListener('mousedown', function (event) {
var event = event || window.event;
mouseOffsetX = event.pageX - this.offsetLeft;
mouseOffsetX = event.pageY - this.offsetTop;
isDrag = true;
});
//鼠标事件2 - 鼠标移动时,如果元素可以拖动,则更新元素的位置到当前鼠标的位置
document.onmousemove = function (event) {
var event = event || window.event;
var mouseX = event.pageX; //鼠标当前位置
var mouseY = event.pageY;
var elementX = 0;//浮层元素的新位置
var elementY = 0;
if (isDrag === true) {
elementX = mouseX - mouseOffsetX;
elementY = mouseY - mouseOffsetY;
//范围限定: elementX > 0 并且 elementX < (页面最大宽度 - 浮层的宽度);
// elementY > 0 并且 elementY < (页面最大高度 - 浮层的高度);
//页面可视区宽度和高度
var pageWidth = document.documentElement.clientWidth;
var pageHeight = document.documentElement.clientHeight;
//浮层元素的宽和高
var elementWith = demo.offsetWidth;
var elementHeight = demo.offsetHeight;
//浮层元素可移动的坐标最大值
var maxX = pageWidth - elementWith;
var maxY = pageHeight - elementHeight;
elementX = Math.min(maxX, Math.max(0, elementX));
elementY = Math.min(maxY, Math.max(0, elementY));
demo.style.left = elementX + 'px';
demo.style.top = elementY + 'px';
}
}
//鼠标事件3 - 鼠标松开的时候(标记元素不可以拖拽),防止鼠标拖拽过快,导致鼠标不在div框内,将事件绑定在document上
window.onmouseup = function() {
isDrag = false;
};
</script>
</body>
</html>