setPointerCapture 是否仅适用于 pointerDown 事件?

Does setPointerCapture works only for pointerDown event?

MDN 说:

The setPointerCapture() method of the Element interface is used to designate a specific element as the capture target of future pointer events. Subsequent events for the pointer will be targeted at the capture element until capture is released.

如果我在 pointerDown 回调中调用 setPointerCapture,它会按预期工作:example - 在这里你可以尽可能快地拖动黄色方块,它会跟随光标直到pointerUp 事件发生。

但如果尝试在 pointerMove 回调中捕获目标,它将不会像我预期的那样工作:example - 黄色方块跟随光标,直到光标悬停在方块上。如果鼠标移动得太快,方块就会停止。

如何解释这种行为?我是不是误解了文档?

不完全是。

The specs ask that

The pointer MUST be in its active buttons state for this method to be effective, otherwise it fails silently.

进入 its active buttons state 意味着:

The condition when a pointer has a non-zero value for the buttons property. For mouse, this is when the device has at least one button depressed. For touch, this is when there is physical contact with the digitizer. For pen, this is when either the pen has physical contact with the digitizer, or at least one button is depressed while hovering.

因此,如果您的指针设备在您第一次将它移到您的元素上时处于此状态,或者从与此相关的任何其他事件开始,它应该工作,直到您释放您的指针设备。
但是请注意,要使您的代码在 Firefox 中运行,您需要 preventDefault() pointerdown 事件。但是从 Chrome 开始,您可以使用鼠标设备从元素外部拖动开始,然后移到它上方,捕获将按预期进行。

您的代码的问题是它不检查捕获是否有效,无条件地引发 captured 标志。检查 element.hasPointerCapture(e.pointerId).

而不是此标志