一定要给documentElement 或者 onwerDocument 绑定鼠标移动事件,否则鼠标脱离可视区域将无法继续拖动元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
height: 100%;
width: 100%;
background: lightblue;
padding: 0;
margin: 0;
}
.mask {
position: relative;
width: 100%;
height: 100%;
background: rgba(1, 1, 1, 0.5);
overflow: hidden;
}
.move {
height: 200px;
width: 300px;
background: yellow;
position: absolute;
cursor: pointer;
left: 100px;
top: 100px;
/* transform: translate(10px,20px); */
}
</style>
</head>
<body>
<div class="mask">
<div class="move"></div>
</div>
</body>
<script>
window.onload = function () {
let move = document.getElementsByClassName('move')[0]
let mask = document.getElementsByClassName('mask')[0]
// let dom = move.ownerDocument
let dom = document.documentElement
let x //保存上一次的鼠标位置
let y //保存上一次的鼠标位置
let oldL //保存上一次鼠标的位移
let oldY //保存上一次鼠标的位移
let mousemove = function (e) {
move.style.left = e.clientX - x + oldL + 'px'
move.style.top = e.clientY - y + oldY + 'px'
}
let mousedownEv = function (e) {
x = e.clientX
y = e.clientY
oldL = move.style.left ? parseInt(move.style.left) : parseInt(window.getComputedStyle(move).left) //第一次获取不到css标签中的值
oldY = move.style.top ? parseInt(move.style.top) : parseInt(window.getComputedStyle(move).top) //第一次获取不到css标签中的值
dom.addEventListener('pointermove', mousemove)
}
//绑定事件
dom.addEventListener('mousedown', mousedownEv)
dom.addEventListener('mouseup', function (e) {
dom.removeEventListener('pointermove', mousemove)
console.log('up')
})
}
</script>
</html>
代码可能实现的有些不太灵活欢迎指出