<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background-color: greenyellow;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
isDown = false
box.onmousedown = function(){
console.log("down")
isDown = true
}
box.onmouseup = function(){
console.log("up")
// document.onmousemove = null
isDown = false
}
document.onmousemove = function(event){//在document范围内移动,给document绑定移动事件
// console.log("move")
//将盒子的中心移动到点击处(事件源)
if(!isDown) return
var x = event.clientX - box.offsetWidth/2
var y = event.clientY - box.offsetHeight/2
if(y<=0) y=0
if(x<=0) x=0
if(x>=document.documentElement.clientWidth-box.offsetWidth)
x=document.documentElement.clientWidth-box.offsetWidth
if(y>=document.documentElement.clientHeight-box.offsetHeight)
y=document.documentElement.clientHeight-box.offsetHeight
box.style.left = x+"px"//相对于窗口移动
box.style.top = y+"px"
}
</script>
</body>
</html>
效果显示: