一、效果图
二、使用步骤
1.html代码
代码如下(示例):
<div id="parent">
<div id="child"></div>
</div>
1.css代码
代码如下(示例):
* {
padding: 0;
margin: 0;
}
#parent {
position: relative;
margin: auto;
width: 800px;
height: 600px;
border: 20px solid blue;
}
#child {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
2.js代码
代码如下(示例):
var parent = document.getElementById('parent')
var child = document.getElementById('child')
var leftObj = 0
var topObj = 0
// 添加事件 按下
child.onmousedown = function () {
console.log('测试');
// 给文档绑定移动事件
document.onmousemove = function (event) {
console.log('移动了');
var event = event || window.event
// 鼠标距离左侧的距离-最外层盒子距离左侧的距离-最外层盒子的边框-小盒子宽度的一半
leftObj = event.clientX - parent.offsetLeft - parent.clientLeft - child.clientWidth / 2
topObj = event.clientY - parent.offsetTop - parent.clientTop - child.clientHeight / 2
// 判断临界值
var MaxX = parent.clientWidth - child.clientWidth
var MaxY = parent.clientHeight - child.clientHeight
if (leftObj > MaxX) {
leftObj = MaxX
}
if (leftObj < 0) {
leftObj = 0
}
if (topObj > MaxY) {
topObj = MaxY
}
if (topObj < 0) {
topObj = 0
}
child.style.top = topObj + 'px'
child.style.left = leftObj + 'px'
}
}
// 清除移动事件
document.onmouseup = function () {
document.onmousemove = null
}