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

后端 未结 9 841
无人及你
无人及你 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.

提交回复
热议问题