<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
width: 300px;
height: 300px;
background:
position: absolute;
}
</style>
</head>
<body>
<div id="demo">123</div>
<script>
//先画个定位的DIV
let demo = document.querySelector('#demo')
//定义一个变量来标记是否按下
let canMove = false
let x =0,y=0
//监听Mousedown mouseup mousemove
demo.onmousedown = function (e) {
canMove = true
x = e.pageX - demo.offsetLeft
y = e.pageY - demo.offsetTop
}
window.onmouseuo = function () {
canMove = false
}
//监听blur事件,防止窗口失去焦点导致bug
window.onblur = function () {
canMove = false
}
window.onmousemove = function (e) {
//在move时阻止默认行为,防止拖动文字有Bug
e.preventDefault()
//在Move中判断如果按下,则将鼠标位置赋值给div
if (canMove) {
//按下时记录鼠标与div的相对位置,移动时减去这段距离
let left = e.pageX-x
let top = e.pageY-y
//限制div移动距离不能超过当前页面
let maxLeft = window.innerWidth - demo.offsetWidth
let maxTop = window.innerHeight - demo.offsetHeight
if (left < 0) left = 0
if (top < 0) top = 0
if (left > maxLeft) left = maxLeft
if (top > maxTop) top = maxTop
demo.style.left = left + 'px'
demo.style.top = top + 'px'
}
}
</script>
</body>