首先我们要写出基本样式
HTML
<div class="bigbox">
<div class="smallbox"></div>
</div>
css
* {
padding: 0;
margin: 0;
}
html,body {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.bigbox {
width: 1000px;
height: 600px;
border: 1px solid red;
position: relative;
}
.smallbox {
width: 100px;
height: 100px;
background-color: pink;
cursor: move;
position: absolute;
}
我们先来分析一下小盒子,大盒子之间的距离问题
然后我们来写js的代码
// 获取元素
var box1 = document.querySelector('.bigbox')
var box2 = document.querySelector('.smallbox')
box2.onmousedown = function (event) {
var event = event || window.event
var width = event.offsetX
var height = event.offsetY
document.onmousemove = function (event) {
var event = event || window.event
var x = event.pageX - box2.offsetParent.offsetLeft - width
var y = event.pageY - box2.offsetParent.offsetTop - height
console.log('x', x)
console.log('y', y)
console.log(box2.offsetParent.offsetLeft)
//判断边界值
if (x <= 0) {
x = 0
}
if (x >= box1.clientWidth - box2.clientWidth) {
x = box1.clientWidth - box2.clientWidth
}
if (y <= 0) {
y = 0
}
if (y >= box1.clientHeight - box2.clientHeight) {
y = box1.clientHeight - box2.clientHeight
}
box2.style.left = x + 'px'
box2.style.top = y + 'px'
}
}
document.onmouseup = function () {
document.onmousemove = null
}