我正在听mousemove事件,以基于鼠标位置为按钮提供良好的效果。但是在移动设备上,如果我触摸该按钮,则事件也会触发,并使该按钮跳转到该位置。我宁愿让按钮在触摸操作时忽略事件,但我仍在努力了解如何实现此目的?

// The function is just a helper of mine (it ads addEventListener to the matched events
createEventListener('.hoverable', 'mousemove', function(e) {
  // stripped out some calculations for simplicity reasons
  const deltaX = 50;
  const deltaY = 50;

  const transformString = `translate3d(${deltaX}px, ${deltaY}px, 0)`;

  this.style.mozTransform = transformString;
  this.style.webkitTransform = transformString;
  this.style.transform = transformString;
});

最佳答案

您可以在元素中添加CSS样式:触摸操作。

style="touch-action: none;"

或添加/删除事件并取消该事件的操作:

因此触发的事件顺序为:1)touchstart 2)touchmove 3)touchend 4)mousemove 5)mousedown 6)mouseup 7)单击。

也许是这样的:
function handleTouch(e) {
  e.preventDefault();
}
document.getElementsByClassName("hoverable").addEventListener('touchstart', handleTouch, false);

document.getElementsByClassName("hoverable").removeEventListener('touchstart', handleTouch);

07-24 18:59
查看更多