<div id="app">
<div class="box"></div>
safsafa
</div>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 100px;
height: 100px;
position: absolute;
background: red;
}
</style>
let box = document.querySelector(".box");
box.onmousedown = function (e) {
let x = e.clientX - this.offsetLeft;
let y = e.clientY - this.offsetTop;
document.onmousemove = function (e) {
let leftX = e.clientX - x;
let topY = e.clientY - y;
let maxLeft = innerWidth - box.offsetWidth;
let maxTop = innerHeight - box.offsetHeight;
if (leftX < 0) {
leftX = 0;
}
if (topY < 0) {
topY = 0;
}
if (leftX > maxLeft) {
leftX = maxLeft;
}
if (topY > maxTop) {
topY = maxTop;
}
box.style.left = leftX + "px";
box.style.top = topY + "px";
};
document.onmouseup = function () {
box.onmouseup = null;
document.onmousemove = null;
};
return false;
};