当检测到pointermove时,链接上的鼠标操作不会触发pointerup事件

2024-01-16

我无法获取pointerup在链接上触发的事件(A带有一个标签href属性集)对于event.pointerType == 'mouse'如果鼠标在之间移动pointerdown and pointerup.

我有以下场景:

var lastEvent = false;
var handler = function (e) {
  if (lastEvent != e.type) {
    e.target.innerHTML += e.type + ' with ' + e.pointerType + '<br/>';
    e.target.scrollTo(0, e.target.scrollHeight);
  }
  lastEvent = e.type;
}
document.querySelector('a').addEventListener('pointerdown', handler);
document.querySelector('a').addEventListener('pointermove', handler);
document.querySelector('a').addEventListener('pointerup', handler);
div {
  height: 100vh;
  display: flex;
}
a {
  height: 60vh;
  width: 75vw;
  margin: auto;
  background-color: red;
  display: inline-block;
  user-select: none;
  touch-action: none;
  overflow-y: scroll;
}
<div>
    <a href="#"></a>
</div>

如果我按下鼠标按钮,按住一段时间然后松开,我会得到以下序列:

  1. 用鼠标指针向下
  2. 用鼠标指针向上

但是,如果我按下鼠标按钮,保持按下状态并移动鼠标指针,然后释放它,我会得到以下序列:

  1. 用鼠标指针向下
  2. 指针随鼠标移动

问题:指针永远不会触发。

我猜这是浏览器中内置的点击或拖动功能(我已经在 Chrome 中进行了测试)阻止了pointerup触发事件,因为如果在span或删除href从锚链接来看,它适用于以下序列:

  1. 用鼠标指针向下
  2. 指针随鼠标移动
  3. 用鼠标指针向上

此外,它也可以完美地用于触摸驱动PointerEvents:

  1. 触摸指针向下
  2. 指针通过触摸移动
  3. 触摸时指针向上

我猜想在元素上设置一个聪明的 css 属性来禁用它pointerup预防。就像是a { pointer-actions: click; },但我没能找到什么。


噢!我基本上已经在问题中给出了答案。这是拖动动作这阻止了pointerup射击事件。只需添加draggable="false"链接元素上的属性修复了此问题。

<a href="#" draggable="false"></a>

概念证明:

var lastEvent = false;
var handler = function (e) {
  if (lastEvent != e.type) {
    e.target.innerHTML += e.type + ' with ' + e.pointerType + '<br/>';
    e.target.scrollTo(0, e.target.scrollHeight);
  }
  lastEvent = e.type;
}
document.querySelector('a').addEventListener('pointerdown', handler);
document.querySelector('a').addEventListener('pointermove', handler);
document.querySelector('a').addEventListener('pointerup', handler);
div {
  height: 100vh;
  display: flex;
}
a {
  height: 60vh;
  width: 75vw;
  margin: auto;
  background-color: red;
  display: inline-block;
  user-select: none;
  touch-action: none;
  overflow-y: scroll;
}
<div>
    <a href="#" draggable="false"></a>
</div>

唯一的缺点是draggable set to false, all mousedown-mousemove-mouseup将触发一个click事件。但这可以通过检查是否存在差异来防止clientX/clientY之间pointerdown and pointerup事件大于一定数量的像素,将其存储在变量中并添加click运行的事件处理程序e.preventDefault(); e.stopPropagation();在这种情况下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当检测到pointermove时,链接上的鼠标操作不会触发pointerup事件 的相关文章

随机推荐