看看这个小提琴:演示
我已将两个事件附加到 div 元素,第一个是
mousedown
,第二个是 touchstart
。
当从触摸设备单击元素时,
mousedown
和touchstart
都会被触发,我的期望只是触发相应的事件,即仅需要从移动设备触发“touchstart”。
请看看这个小提琴
通常事件顺序是: 1)
touchstart
2)touchmove
3)touchend
4)mousemove
5) mousedown
6) mouseup
7) click
当任何触摸事件被取消时,鼠标事件将不会被调用。 即使发生触摸移动,鼠标事件也不会发生。 希望这有帮助:)
我测试了Jasmin的解决方案,但它对我不起作用,所以我通过setTimeout处理它
let freezed = false;
let counter = 1;
const onPress = () => {
if(freezed) return;
freezed = true;
setTimeout(() => {
freezed = false;
}, 100);
document.getElementById("counter").innerText = counter++
}
document.getElementById("button").addEventListener("touchstart", onPress);
document.getElementById("button").addEventListener("mousedown", onPress);
<button id="button">
Mouse down or touch me
</button>
<p>Counter: <span id="counter">0</span></p>