代码如下:
<style>
#demo {
width: 300px;
height: 300px;
background: #ccc;
position: absolute;
}
</style>
<body>
<input type="text">
<div id="demo">asdfasf</div>
<script>
let demo = document.querySelector('#demo')
let canMove = false
let x = 0, y = 0
demo.onmousedown = function (e) {
x = e.pageX - demo.offsetLeft
y = e.pageY - demo.offsetTop
canMove = true
}
demo.oncontextmenu = function (e) {
e.preventDefault()//在盒子上右击不会弹出默认菜单
}
setTimeout(() => {
}, 2000);
//鼠标点击与松开事件
window.onmouseup = function () {
canMove = false
}
window.onblur = function () {
canMove = false
}
window.onmousemove = function (e) { //盒子移动的核心事件
e.preventDefault(); //阻止默认行为
if (canMove) {
let left = e.pageX - x
let top = e.pageY - y
if (left < 0) left = 0//使盒子不能拖拽到顶部或左部以外
if (top < 0) top = 0
let maxLeft = window.innerWidth - demo.offsetWidth
let maxTop = window.innerHeight - demo.offsetHeight
if (left > maxLeft) left = maxLeft//通过计算,使盒子不能拖拽到页面屏幕以外
if (top > maxTop) top = maxTop
demo.style.left = left + "px"
demo.style.top = top + 'px'
}
}
</script>
</body>