How to bind 'touchstart' and 'click' events but not respond to both?

前端 未结 30 3363
抹茶落季
抹茶落季 2020-11-22 14:08

I\'m working on a mobile web site that has to work on a variety of devices. The one\'s giving me a headache at the moment are BlackBerry.

We need to support both key

30条回答
  •  一整个雨季
    2020-11-22 14:17

    Just for documentation purposes, here's what I've done for the fastest/most responsive click on desktop/tap on mobile solution that I could think of:

    I replaced jQuery's on function with a modified one that, whenever the browser supports touch events, replaced all my click events with touchstart.

    $.fn.extend({ _on: (function(){ return $.fn.on; })() });
    $.fn.extend({
        on: (function(){
            var isTouchSupported = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
            return function( types, selector, data, fn, one ) {
                if (typeof types == 'string' && isTouchSupported && !(types.match(/touch/gi))) types = types.replace(/click/gi, 'touchstart');
                return this._on( types, selector, data, fn);
            };
        }()),
    });
    

    Usage than would be the exact same as before, like:

    $('#my-button').on('click', function(){ /* ... */ });
    

    But it would use touchstart when available, click when not. No delays of any kind needed :D

提交回复
热议问题