<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: #6ff;
position: absolute;
left: 50px;
top: 50px;
}
.sub {
width: 50px;
height: 50px;
background-color: #f00;
margin-left: 50px;
margin-top: 50px;
}
</style>
<div class="box"></div>
<script>
var oBox = document.querySelector('.box');
var maxTop = document.documentElement.clientHeight - oBox.offsetHeight;
var maxLeft = document.documentElement.clientWidth - oBox.offsetWidth;
oBox.onmousedown = function (e) {
var ev = event || e;
var x = ev.x;
var y = ev.y;
var gapX = x - oBox.offsetLeft;
var gapY = y - oBox.offsetTop;
document.onmousemove = function (e) {
var ev = event || e;
var x = ev.x;
var y = ev.y;
var left = x - gapX;
var top = y - gapY;
if (left < 0) left = 0;
if (left > maxLeft) left = maxLeft;
if (top < 0) top = 0;
if (top > maxTop) top = maxTop;
oBox.style.cssText = `left: ${left}px; top: ${top}px`;
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
</script>