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

后端 未结 9 764
无人及你
无人及你 2020-12-04 14:24

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         


        
相关标签:
9条回答
  • 2020-12-04 15:06

    taking gregers comment on win8 and chrome/firefox into account, skyisred's comment doesn't look that dumb after all (:P @ all the haters) though I would rather go with a blacklist than with a whitelist which he suggested, only excluding Android from touch-binds:

    var ua = navigator.userAgent.toLowerCase(),
    isAndroid = ua.indexOf("android") != -1,
    supportsPointer = !!window.navigator.msPointerEnabled,
    ev_pointer = function(e) { ... }, // function to handle IE10's pointer events
    ev_touch = function(e) { ... }, // function to handle touch events
    ev_mouse = function(e) { ... }; // function to handle mouse events
    
    if (supportsPointer) { // IE10 / Pointer Events
        // reset binds
        $("yourSelectorHere").on('MSPointerDown MSPointerMove MSPointerUp', ev_pointer);
    } else {
        $("yourSelectorHere").on('touchstart touchmove touchend', ev_touch); // touch events
        if(!isAndroid) { 
            // in androids native browser mouse events are sometimes triggered directly w/o a preceding touchevent (most likely a bug)
            // bug confirmed in android 4.0.3 and 4.1.2
            $("yourSelectorHere").on('mousedown mousemove mouseup mouseleave', ev_mouse); // mouse events
        }
    }
    

    BTW: I found that mouse-events are NOT always triggered (if stopPropagation and preventDefault were used), specifically I only noticed an extra mousemove directly before a touchend event... really weird bug but the above code fixed it for me across all (tested OSX, Win, iOS 5+6, Android 2+4 each with native browser, Chrome, Firefox, IE, Safari and Opera, if available) platforms.

    0 讨论(0)
  • 2020-12-04 15:07

    Wow, so many answers in this and the related question, but non of them worked for me (Chrome, mobil responsive, mousedown + touchstart). But this:

    (e) => {
      if(typeof(window.ontouchstart) != 'undefined' && e.type == 'mousedown') return;
    
      // do anything...
    }
    
    0 讨论(0)
  • 2020-12-04 15:07

    This native solution worked best for me:

    1. Add a touchstart event to the document settings a global touch = true.
    2. In the mousedown/touchstart handler, prevent all mousedown events when a touch screen is detected: if (touch && e.type === 'mousedown') return;
    0 讨论(0)
提交回复
热议问题