拖拽_不让用户拖出可视区域

本文最后更新于:2023年3月30日 下午

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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{ margin: 0;padding: 0;list-style: none}
#div{ width: 100px;height: 100px;background: pink;position: absolute;}
</style>
<script>
window.onload = function() {
var odiv = document.getElementById('div');
var disX = 0;
var disY = 0;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
odiv.onmousedown = function(event) {
// 当鼠标按下时计算鼠标与拖拽对象的距离
disX = event.clientX + scrollLeft - div.offsetLeft;
disY = event.clientY + scrollTop - div.offsetTop;
document.onmousemove = function(event) {
// 当鼠标拖动时计算div的位置
var l = event.clientX - disX;
var t = event.clientY - disY;
// 不让用户拖出可视区域
if (l <= 0) {
l = 0;
} else if (l > document.documentElement.clientWidth - odiv.offsetWidth) {
l = document.documentElement.clientWidth - odiv.offsetWidth;
}
if (t < 0) {
t = 0;
} else if (t > document.documentElement.clientHeight - odiv.offsetHeight) {
t = document.documentElement.clientHeight - odiv.offsetHeight;
}
odiv.style.left = l + 'px';
odiv.style.top = t + 'px';
}
document.onmouseup = function() {
document.onmousemove = null; // 当鼠标弹起时移出移动事件
odiv.onmouseup = null; // 移出up事件,清空内存
}
return false; // 低版本出现禁止符号
}
}
</script>
</head>
<body>
<div id="div"></div>
</body>
</html>

拖拽_不让用户拖出可视区域
https://seven3.site/js/拖拽_不让用户拖出可视区域/
作者
Seven3s
发布于
2015年1月24日
许可协议