gpt4 book ai didi

javascript - setPointerCapture 在 Chrome 和 Firefox 中的行为不同

转载 作者:行者123 更新时间:2023-12-02 23:06:32 24 4
gpt4 key购买 nike

我在弹性盒子里有一堆方形 div 。当我在方 block 内按下鼠标按钮时,我希望目标方 block 的背景发生变化。我想捕获鼠标,因此当我将鼠标移到捕获的方 block 之外并释放鼠标按钮时,背景应该变回原来的颜色。

这有点难以描述,所以这是代码。 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. 按住鼠标左键,将鼠标拖动到方 block 之外。
  3. 松开鼠标左键。

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

我 try catch 窗口和文档的事件。

编辑: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 的属性界面。

MouseEvents(例如 mousedown)不是从 PointerEvent 继承的,并且没有 pointerId 属性。

您想要的是监听 pointerdownpointerup 事件:

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

Firefox 将 undefined 转换为 0,而 Chrome 则不然,这是一个不幸的差异,但最终没有浏览器真正做到了你所期望的,因为你的代码在这里被破坏了。

关于javascript - setPointerCapture 在 Chrome 和 Firefox 中的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57566090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com