一定要給documentElement 或者 onwerDocument 綁定鼠標(biāo)移動事件,否則鼠標(biāo)脫離可視區(qū)域?qū)o法繼續(xù)拖動元素
<!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 //保存上一次的鼠標(biāo)位置
let y //保存上一次的鼠標(biāo)位置
let oldL //保存上一次鼠標(biāo)的位移
let oldY //保存上一次鼠標(biāo)的位移
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標(biāo)簽中的值
oldY = move.style.top ? parseInt(move.style.top) : parseInt(window.getComputedStyle(move).top) //第一次獲取不到css標(biāo)簽中的值
dom.addEventListener('pointermove', mousemove)
}
//綁定事件
dom.addEventListener('mousedown', mousedownEv)
dom.addEventListener('mouseup', function (e) {
dom.removeEventListener('pointermove', mousemove)
console.log('up')
})
}
</script>
</html>
代碼可能實現(xiàn)的有些不太靈活歡迎指出