Prevent click event from firing when dblclick event fires

前端 未结 12 1330
名媛妹妹
名媛妹妹 2020-12-02 20:17

I\'m handling both the click and dblclick event on a DOM element. Each one carries out a different command, but I find that when double clicking on the element, in addition

12条回答
  •  广开言路
    2020-12-02 20:50

    Thanks to all the other answers here as the combination of them seems to provide a reasonable solution for me when the interaction requires both, but mutually exclusive:

    var pendingClick = 0;
    
    function xorClick(e) {
        // kill any pending single clicks
        if (pendingClick) {
            clearTimeout(pendingClick);
            pendingClick = 0;
        }
    
        switch (e.detail) {
            case 1:
                pendingClick = setTimeout(function() {
                    console.log('single click action here');
                }, 500);// should match OS multi-click speed
                break;
            case 2:
                console.log('double click action here');
                break;
            default:
                console.log('higher multi-click actions can be added as needed');
                break;
        }
    }
    
    myElem.addEventListener('click', xorClick, false);
    

    Update: I added a generalized version of this approach along with a click polyfill for touch devices to this Github repo with examples:

    https://github.com/mckamey/doubleTap.js

提交回复
热议问题