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

前端 未结 30 3373
抹茶落季
抹茶落季 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:11

    Here's a simple way to do it:

    // A very simple fast click implementation
    $thing.on('click touchstart', function(e) {
      if (!$(document).data('trigger')) $(document).data('trigger', e.type);
      if (e.type===$(document).data('trigger')) {
        // Do your stuff here
      }
    });
    

    You basically save the first event type that is triggered to the 'trigger' property in jQuery's data object that is attached to the root document, and only execute when the event type is equal to the value in 'trigger'. On touch devices, the event chain would likely be 'touchstart' followed by 'click'; however, the 'click' handler won't be executed because "click" doesn't match the initial event type saved in 'trigger' ("touchstart").

    The assumption, and I do believe it's a safe one, is that your smartphone won't spontaneously change from a touch device to a mouse device or else the tap won't ever register because the 'trigger' event type is only saved once per page load and "click" would never match "touchstart".

    Here's a codepen you can play around with (try tapping on the button on a touch device -- there should be no click delay): http://codepen.io/thdoan/pen/xVVrOZ

    I also implemented this as a simple jQuery plugin that also supports jQuery's descendants filtering by passing a selector string:

    // A very simple fast click plugin
    // Syntax: .fastClick([selector,] handler)
    $.fn.fastClick = function(arg1, arg2) {
      var selector, handler;
      switch (typeof arg1) {
        case 'function':
          selector = null;
          handler = arg1;
          break;
        case 'string':
          selector = arg1;
          if (typeof arg2==='function') handler = arg2;
          else return;
          break;
        default:
          return;
      }
      this.on('click touchstart', selector, function(e) {
        if (!$(document).data('trigger')) $(document).data('trigger', e.type);
        if (e.type===$(document).data('trigger')) handler.apply(this, arguments);
      });
    };
    

    Codepen: http://codepen.io/thdoan/pen/GZrBdo/

提交回复
热议问题