Capture “tap” event with pure JavaScript

后端 未结 4 580
囚心锁ツ
囚心锁ツ 2020-12-23 16:20

How can I capture a user\'s \"tap\" event with pure JS? I cannot use any libraries, unfortunately.

4条回答
  •  余生分开走
    2020-12-23 17:17

    This is not my code but I can't remember where I got it from, used successfully. It uses jQuery but no extra libraries or plugins for the tap handling itself.

    $.event.special.tap = {
        setup: function(data, namespaces) {
            var $elem = $(this);
            $elem.bind('touchstart', $.event.special.tap.handler)
                 .bind('touchmove', $.event.special.tap.handler)
                 .bind('touchend', $.event.special.tap.handler);
        },
    
        teardown: function(namespaces) {
            var $elem = $(this);
            $elem.unbind('touchstart', $.event.special.tap.handler)
                 .unbind('touchmove', $.event.special.tap.handler)
                 .unbind('touchend', $.event.special.tap.handler);
        },
    
        handler: function(event) {
            event.preventDefault();
            var $elem = $(this);
            $elem.data(event.type, 1);
            if (event.type === 'touchend' && !$elem.data('touchmove')) {
                event.type = 'tap';
                $.event.handle.apply(this, arguments);
            } else if ($elem.data('touchend')) {
                $elem.removeData('touchstart touchmove touchend');
            }
        }
    };
    
    $('.thumb img').bind('tap', function() {
        //bind tap event to an img tag with the class thumb
    }
    

    I used this for a project exclusively for iPad, so might need tweaking to work for desktop and tablet together.

提交回复
热议问题