让一个长宽100px的div 在一个长宽为600px的div中拖拽 并且判断边界值
HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 600px;
height: 600px;
border: 1px solid red;
margin: 50px auto;
position: relative;
}
.box2 {
width: 100px;
height: 100px;
background-color: aqua;
position: absolute;
cursor: move;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
JavaScript部分
<script>
// 获取元素
var box2 = document.querySelector('.box2')
//初始化
init()
function init() {
handleDown()
handleUp()
}
// 绑定按下事件
function handleDown() {
box2.onmousedown = function (e) {
//兼容写法
//作用:记录当次事件触发的时候的所有信息 保存在一个对象里面的
var e = e || window.event
//offsetX,offsetY
//以当前触发的目标元素的内边框的左上角为坐标原点
var w = e.offsetX
var h = e.offsetY
handleMove(w, h)
}
}
// 绑定移动事件
function handleMove(w, h) {
document.onmousemove = function (e) {
var e = e || window.event
//pageX,pageY
//以当前document文档的左上角为坐标原点
var x = e.pageX - w - box2.offsetParent.offsetLeft
var y = e.pageY - h - box2.offsetParent.offsetTop
//box2.offsetParent.offsetLeft,box2.offsetParent.offsetTop
//求的是box1的相对位置
// 判断边界值
//让box2不能脱离box1边界
if (x < 50) {
x = 0
}else if(x >box2.offsetParent.offsetWidth - box2.offsetWidth){
//box1的宽度-box2的宽度,剩下的宽度就是边界
//box2.offsetParent.offsetWidth=box1.offsetWidth
x = box2.offsetParent.offsetWidth - box2.offsetWidth
//如果触碰到边界,那么就让box2的左距离等于box1的宽度-box2的宽度
}
if (y < 50) {
y = 0
}else if(y>box2.offsetParent.offsetHeight - box2.offsetHeight){
y = box2.offsetParent.offsetHeight - box2.offsetHeight
}
box2.style.left = x + 'px'
box2.style.top = y + 'px'
}
}
// 绑定抬起事件
//鼠标抬起时,鼠标移动事件为空取消
function handleUp() {
document.onmouseup = function () {
document.onmousemove = null
}
}
</script>
边界值