老师,点击空白处,不能移动,是什么原因呢
<!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> #box { width: 200px; height: 200px; background-color: red; } </style> </head> <body> <div id="box"></div> <script> // 拖拽事件 const drag = $el => { // 每次拖拽最开始的触摸点 const startPoint = {}; // 拖拽过程中移动到的点 const movePoint = {}; // 被拖拽元素的当前位置 const curPos = { x: 0, y: 0 }; $el.addEventListener('pointerdown', startHandler, false); // 绑定触摸事件 $el.addEventListener('touchstart', evt => { evt.preventDefault(); }, false); function startHandler(evt) { // 获取触摸点 startPoint.x = evt.pageX; startPoint.y = evt.pageY; // console.log(startPoint); document.addEventListener('pointermove', moveHandler, false); document.addEventListener('pointerup', endHandler, false); document.addEventListener('pointercancel', endHandler, false); } function moveHandler(e) { e.preventDefault(); movePoint.x = curPos.x + e.pageX - startPoint.x; movePoint.y = curPos.y + e.pageY - startPoint.y; $el.style.transform = `translate3d(${movePoint.x}px,${movePoint.y}px,0)`; } function endHandler() { curPos.x = movePoint.x; curPos.y = movePoint.y; document.removeEventListener('pointermove', moveHandler, false); document.removeEventListener('pointerup', endHandler, false); document.removeEventListener('pointercancel', endHandler, false); } }; drag(document.getElementById('box')); </script> </body> </html>
7
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星