直接上代码
可拖拽div元素在指定区域内移动,不会超出区域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>div 在指定区域内移动</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
#parent {
position: relative;
width: 700px;
height: 470px;
background: gray;
}
#children {
position: absolute;
width: 100px;
height: 100px;
background-color: antiquewhite;
cursor: move;
}
</style>
</head>
<body>
<div id="parent">
<div id="children"></div>
</div>
<script>
window.onload = function () {
var parentNode = document.getElementById("parent");
var childrenNode = document.getElementById("children");
var disX = 0;
var disY = 0;
childrenNode.onmousedown = function (ev) {
//鼠标事件对象
var oEvent = ev || event;
disX = oEvent.clientX - childrenNode.offsetLeft;
disY = oEvent.clientY - childrenNode.offsetTop;
document.onmousemove = function (ev) {
//鼠标事件对象
var oEvent = ev || event;
var l = oEvent.clientX - disX;
var t = oEvent.clientY - disY;
if (l < 50) {
l = 0;
} else if (l > parentNode.clientWidth - childrenNode.offsetWidth) {
l = parentNode.clientWidth - childrenNode.offsetWidth;
}
if (t < 50) {
t = 0;
} else if (t > parentNode.clientHeight - childrenNode.offsetHeight) {
t = parentNode.clientHeight - childrenNode.offsetHeight;
}
childrenNode.style.left = l + "px";
childrenNode.style.top = t + "px";
/**如果父盒子设置有marginTop和marginLeft则需要将其设置为0*/
childrenNode.style.marginLeft = 0;
childrenNode.style.marginTop = 0;
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
//阻止默认事件
return false;
}
}
</script>
</body>
</html>