Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

javascript - How to bind both Mousedown and Touchstart, but not respond to both? Android, JQuery

Working on a website that is also viewable on mobile and need to bind an action on both touchstart and mousedown.

Looks like this

 $("#roll").bind("mousedown touchstart", function(event){

 someAction();

It works fine on Iphone, but on Android it responds twice.

event.stopPropagation();
event.preventDefault();

Adding this code fixed it for Android Chrome, but NOT for Android default browser. Any other tricks that can fix the problem for all android?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
element.on('touchstart mousedown', function(e) {
    e.preventDefault();
    someAction();
});

preventDefault cancels the event, as per specs

You get touchstart, but once you cancel it you no longer get mousedown. Contrary to what the accepted answer says, you don't need to call stopPropagation unless it's something you need. The event will propagate normally even when cancelled. The browser will ignore it, but your hooks will still work.

Mozilla agrees with me on this one:

calling preventDefault() on a touchstart or the first touchmove event of a series prevents the corresponding mouse events from firing

EDIT: I just read the question again and you say that you already did this and it didn't fix the Android default browser. Not sure how the accepted answer helped, as it does the same thing basically, just in a more complicated way and with an event propagation bug (touchstart doesn't propagate, but click does)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...