繁体   English   中英

"setPointerCapture 在 Chrome 和 Firefox 中的行为不同"

[英]setPointerCapture behaves differently in Chrome and Firefox

我在 flexbox 中有一堆方形 div。 当我在正方形内按下鼠标按钮时,我希望目标正方形的背景发生变化。 我想捕获鼠标,所以当我将鼠标移到捕获的正方形外并释放鼠标按钮时,背景应该变回原来的颜色。

这有点难以描述,所以这里是代码。 https://codepen.io/tqphan/pen/qBWaVod

window.addEventListener('mousedown', function(e) {
  e = e || window.event;
  var target = e.target || e.srcElement;
  target.classList.add("pressed")
  target.setPointerCapture(e.pointerId);
}, true);
window.addEventListener('mouseup', function(e) {
  e = e || window.event;
  var target = e.target || e.srcElement;
  target.classList.remove("pressed")
  target.releasePointerCapture(e.pointerId);
}, true);

要重现此问题,请按照下列步骤操作:

  1. 在正方形上按鼠标左键。
  2. 在按住鼠标左键的同时,将鼠标拖到方块外。
  3. 松开鼠标左键。

在 Firefox 中,它按我的预期工作。 在 Chrome 中,背景不会变回原来的颜色。

我尝试捕获窗口和文档的事件。

编辑:似乎指针捕获和释放没有在 Chrome 中执行。

pen.js:6 Uncaught DOMException: Failed to execute 'setPointerCapture' on 'Element': No active pointer with the given id is found.

pen.js:12 Uncaught DOMException: Failed to execute 'releasePointerCapture' on 'Element': No active pointer with the given id is found.

pointerIdPointerEvent接口的属性。

像mousedown这样的MouseEvents不会从PointerEvent继承,也没有pointerId属性。

您想要的是监听pointerdownpointerup事件:

 onmousedown = e => console.log('mousedown', e.pointerId) // undefined onpointerdown = e => console.log('pointerdown', e.pointerId) // id 

不幸的是,Firefox将undefined0而Chrome并非如此,但是最终,没有浏览器真正做到了您的期望,因为您的代码在这里被破坏了。

我遇到了相同或类似的问题,setPointerCapture() 在 FireFox 上非常适合我的应用程序,但在 Chrome 上却不行。 在 Chrome 上,它似乎什么也没做,也没有错误消息。

我终于明白为什么了。 在 Chrome 上 setPointerCapture() 似乎只捕获“指针事件”,这意味着事件名为“pointermove”和“pointerup”,而不是事件“mousemove”和“mouseup”等。这发生在 Chrome 版本 97.0.4692.99(官方构建)(64-少量)

在 FireFox 上,setPointerCapture()还<\/em>捕获“鼠标事件”,例如“mousemove”和“mouseup”。 这些是我在我的 DOM 元素中设置事件处理程序的那些。 因此他们在 FireFox 上运行良好。

解决方案是修改我的代码,而不是为“ mousemove<\/strong> ”和“ mouseup<\/strong> ”添加处理程序,我现在为“ pointermove<\/strong> ”和“ pointerup<\/strong> ”添加处理程序。 在此更改之后,它在 FireFox 和 Chrome 上同样适用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM