DOM元素移动后Pointermove事件停止触发的问题解决咨询
DOM元素移动后Pointermove事件停止触发的问题解决咨询
我碰到了个拖拽元素的小麻烦:当把绿色方块拖到其他方块上方时,它会被插入到目标方块前面(完成位置移动),但要是不松开鼠标继续拖拽,后续经过其他方块时这个移动操作就不管用了。目前onpointermove事件只在绿色按钮自己上方触发,不会响应DOM里其他区域的指针移动。
我推测这应该和元素在DOM结构中被移动了有关,有没有大佬能指点下怎么绕开这个问题?我必须用Pointer Capture API来实现这个拖拽功能。
相关代码
JavaScript
const divs = Array.from(document.querySelectorAll("div")); divs.forEach((div) => { function beginSliding(e) { div.onpointermove = slide; div.setPointerCapture(e.pointerId); } function stopSliding(e) { div.onpointermove = null; div.releasePointerCapture(e.pointerId); } function slide(e) { const ele = document.elementFromPoint(e.clientX, e.clientY); console.log("move"); if (ele === e.target || !divs.includes(ele)) { return; } div.parentElement.insertBefore(div, ele) } div.onpointerdown = beginSliding; div.onpointerup = stopSliding; });
CSS
nav { display: flex; gap: 10px; } div { height: 30px; width: 100px; user-select: none; } #a { background: grey; } #b { background: red; } #c { background: blue; } #d { background: yellow; } #e { background: green; }
HTML
<nav> <div id="a"></div> <div id="b"></div> <div id="c"></div> <div id="d"></div> <div id="e"></div> </nav>
备注:内容来源于stack exchange,提问作者Cheetah
相关产品推荐
相关产品推荐

