PC端点击空白处也可以拖拽是不是有问题?
<!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>
div {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script>
const box = document.getElementById('box');
const drag = (ele) => {
const startPoint = {};
const movePoint = {};
const currentPoint = {
x: 0,
y: 0
}
document.addEventListener('pointerdown', startP, false)
ele.addEventListener('touchstart', (e) => {
e.preventDefault()
}, false)
function startP(e){
startPoint.x = e.pageX;
startPoint.y = e.pageY;
document.addEventListener('pointermove', moveP, false)
document.addEventListener('pointerup', upP, false)
document.addEventListener('pointercancel', upP, false)
}
function moveP(e){
movePoint.x = currentPoint.x + e.pageX - startPoint.x;
movePoint.y = currentPoint.y + e.pageY - startPoint.y;
ele.style.transform = `translate3d(${movePoint.x}px,${movePoint.y}px,0)`
e.preventDefault()
}
function upP(e){
currentPoint.x = movePoint.x;
currentPoint.y = movePoint.y;
document.removeEventListener('pointermove', moveP, false)
document.removeEventListener('pointerup', upP, false)
document.removeEventListener('pointercancel', upP, false)
}
}
drag(box);
</script>
</html>老师你好,点击空白处也可以拖拽,是不是代码哪里错了
13
收起
正在回答
1回答
同学你好,监听元素的问题,将按下事件绑定在box元素上,点击空白处就不会拖拽了

祝学习愉快!

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星