You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:19:31