代码实现
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#box{
position: absolute;
width:400px;
height:300px;
background-color: red;
}
</style>
<body>
<div id="box"></div>
<script>
let box = document.getElementById("box")
box.onmousedown = function(e){
let offsetX = e.offsetX
let offsetY = e.offsetY
document.onmousemove = function(e2){
let clientX = e2.clientX
let clientY = e2.clientY
_left = clientX - offsetX
_top = clientY - offsetY
if(_left < 0){
_left = 0
}
if(_top < 0){
_top = 0
}
if(_left > document.documentElement.clientWidth - box.offsetWidth){
_left = document.documentElement.clientWidth - box.offsetWidth
}
box.style.left = _left + "px"
box.style.top = _top + "px"
}
}
document.onmouseup = function(){
document.onmousemove = null
}
</script>
</body>
</html>
网页效果
image.png