setPointerCapture是否仅适用于pointerDown事件? [英] Does setPointerCapture works only for pointerDown event?

查看:183
本文介绍了setPointerCapture是否仅适用于pointerDown事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN 说:

Element接口的setPointerCapture()方法用于将特定元素指定为将来的指针事件的捕获目标.指针的后续事件将针对捕获元素直到捕获被释放.

如果我在 pointerDown 回调中调用 setPointerCapture ,它会按预期工作:示例-您可以在此处随意拖动黄色正方形,它将跟随光标直到发生 pointerUp 事件.

And it works as expected if I call setPointerCapture in pointerDown callback: example - here you can drag yellow square as fast as you want and it will follow the cursor until pointerUp event happens.

但是,如果尝试在 pointerMove 回调中捕获目标,则它将无法正常工作:示例-黄色正方形跟随光标,直到光标悬停在正方形上.如果您将鼠标移动得太快,正方形将停止.

But if try to capture target in pointerMove callback it won't work as I expected: example - yellow square follows the cursor until cursor hovers the square. If you move your mouse too fast square will stopped.

如何解释这种行为?我误会了文档吗?

How this behavior can be explained? Did i misunderstand the documentation?

推荐答案

不完全是

规范要求

指针必须处于其活动按钮状态,此方法才能生效,否则它会无提示地失败.

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

要进入其活动按钮状态意味着:

按钮属性的指针具有非零值时的条件.对于鼠标,这是指设备按下至少一个按钮时的状态.对于触摸,这是当与数字转换器物理接触时.对于笔,这是指笔与数字转换器物理接触,或者在悬停时至少按下了一个按钮.

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使用鼠标设备开始,您可以先将其拖动到元素的外部,然后将其移到该元素上,然后捕获将按预期进行.

So if your pointer device is in this state when you first move it over your element, or from any other event for that matter, it should work, until you release your pointer device.
However note that for your code to work in Firefox you need to preventDefault() the pointerdown event. But from Chrome, with a mouse device, you can start by dragging outside of the element, then move over it and the capture will work as intended.

您的代码存在的问题是,它不会检查捕获是否确实有效,因此会无条件提高 captured 标志.代替此标志,检查 element.hasPointerCapture(e.pointerId) .

The problem with your code is that it doesn't check if the capture did work, raising the captured flag unconditionally. Instead of this flag, check for element.hasPointerCapture(e.pointerId).

这篇关于setPointerCapture是否仅适用于pointerDown事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆