拖拽+边界值限定
<style>
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.move-box{
width: 420px;
height: 560px;
background:#f40 ;
position: absolute;
margin: 0 auto;
top: 30px;
left: 30px;
}
.move-model{
position: relative;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="move-box">宽100高100</div>
<script>
let draw = document.getElementsByClassName('move-box')[0]
// 盒子宽高
let width = draw.offsetWidth
let height = draw.offsetHeight
// 记录鼠标按下位置
let dX,dY
draw.onmousedown=function(e){
dX = e.offsetX
dY = e.offsetY
// 小细节 移动事件绑定在 document 上
document.onmousemove=function(eD){
let top = eD.pageY - dY
let left = eD.pageX - dX
// 边界值限定
let maxLeft = window.innerWidth - width - 30
let maxTop = window.innerHeight - height - 30
draw.style.top = top > maxTop ? maxTop + 'px' : (top > 30 ? top + 'px' : '30px')
draw.style.left = left > maxLeft ? maxLeft + 'px' : (left > 30 ? left + 'px' : '30px')
}
document.onmouseup = function(e){
if(document.onmousemove && typeof document.onmousemove === 'function'){
document.onmousemove=null
document.onmouseup = null
}
}
// 阻止默认行为
return false
}
</script>
</body>