最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Why Javascript touchstart and mousedown events tiggered at same time? - Stack Overflow

programmeradmin1浏览0评论

Take a look at this fiddle: demo

I have attached two events to the div element first one is mousedown and second one is touchstart.

While clicking the element from the touch device both mousedown and touchstart is getting triggered, my expectation is only to trigger the respective events i.e only `touchstart needs to be triggered from the mobile device.

Take a look at this fiddle: demo

I have attached two events to the div element first one is mousedown and second one is touchstart.

While clicking the element from the touch device both mousedown and touchstart is getting triggered, my expectation is only to trigger the respective events i.e only `touchstart needs to be triggered from the mobile device.

Share Improve this question asked Jan 31, 2018 at 6:02 Mohan RaviMohan Ravi 971 silver badge7 bronze badges 4
  • Why not just add one handler conditionally? – marekful Commented Jan 31, 2018 at 6:04
  • Mobile browsers trigger mousedown and click, too. You can assign the events to a variable. Use Modernizer.js for this. – Adam Azad Commented Jan 31, 2018 at 6:04
  • 1 Take a look at this question for workaround if needed. See MDN for details. – lolbas Commented Jan 31, 2018 at 6:05
  • 1 Touch devices will fire both the events w3c.github.io/touch-events/#mouse-events – karthick Commented Jan 31, 2018 at 6:05
Add a ment  | 

2 Answers 2

Reset to default 6

Please have a look at this fiddle

Normally the event order is : 1) touchstart 2) touchmove 3) touchend 4) mousemove 5) mousedown 6) mouseup 7) click

When any of touch event gets cancelled, then mouse event won't be called. Even if touch move occurs, then mouse event won't occur. Hope this helps :)

I tested Jasmin's solution, but it did not work for me, so I handled it via 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>

发布评论

评论列表(0)

  1. 暂无评论