<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
#div2{
width:400px;
height:400px;
background:#ddd;
position:relative;
}
</style>
</head>
<body>
<!-- 限制物体在另一个物体范围内的运动范围 -->
<div id="div2">
<div id="div1"></div>
</div>
<script>
var div1 = document.getElementById('div1');
var div2=document.getElementById('div2');
div1.onmousedown = function (ev) {
var eve = window.event || ev;
//当前鼠标在物体上 此时鼠标和物体的相对位置距离
var disX = eve.clientX - div1.offsetLeft;
var disY = eve.clientY - div1.offsetTop;
//当鼠标移动位置后 物体的位置=最新鼠标位置-相对位置距离
document.onmousemove = function (ev) {
var eve = window.ev || ev;
var l = eve.clientX - disX;
var t = eve.clientY - disY;
// l,t 是物体的位置
//
if (l < 50) {
l = 0;
}//磁浮拖拽
else if (l > div2.offsetWidth - div1.offsetWidth) {
l = div2.offsetWidth - div1.offsetWidth;
}
if (t < 50) {
t = 0;
} else if (t > div2.offsetHeight - div1.offsetHeight) {
t = div2.offsetHeight - div1.offsetHeight;
}
div1.style.left = l + 'px';
div1.style.top = t + 'px';
}
//mousemove mouseup都加到document中防止鼠标快速移动的时候脱离物体
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
return false;//火狐的bug当是空div的时候会出现半透明情况
}
</script>
</body>
</html>
</body>
</html>