How do I listen for triple clicks in JavaScript?

后端 未结 6 1494
Happy的楠姐
Happy的楠姐 2020-12-02 16:38

If this is for a double-click:

window.addEventListener(\"dblclick\", function(event) { }, false);

How can I capture a triple-click? This is

6条回答
  •  一向
    一向 (楼主)
    2020-12-02 17:14

    I am working on a javascript code editor and I had to listen for triple click and here is the solution that will work for most browsers:

    // Function to get mouse position
    var getMousePosition = function (mouseEvent) {
        var currentObject = container;
        var currentLeft = 0;
        var currentTop = 0;
        do {
            currentLeft += currentObject.offsetLeft;
            currentTop += currentObject.offsetTop;
            currentObject = currentObject.offsetParent;
        } while (currentObject != document.body);
        return {
            x: mouseEvent.pageX - currentLeft,
            y: mouseEvent.pageY - currentTop
        }
    }
    
    // We will need a counter, the old position and a timer
    var clickCounter = 0;
    var clickPosition = {
        x: null,
        y: null
    };
    var clickTimer;
    
    // The listener (container may be any HTML element)
    container.addEventListener('click', function (event) {
    
        // Get the current mouse position
        var mousePosition = getMousePosition(event);
    
        // Function to reset the data
        var resetClick = function () {
            clickCounter = 0;
            var clickPosition = {
                x: null,
                y: null
            };
        }
    
        // Function to wait for the next click
        var conserveClick = function () {
            clickPosition = mousePosition;
            clearTimeout(clickTimer);
            clickTimer = setTimeout(resetClick, 250);
        }
    
        // If position has not changed
        if (clickCounter && clickPosition.x == mousePosition.x && clickPosition.y == mousePosition.y) {
            clickCounter++;
            if (clickCounter == 2) {
                // Do something on double click
            } else {
                // Do something on triple click
                resetClick();
            }
            conserveClick();
        } else {
            // Do something on single click
            conserveClick();
        }
    });
    

    Tested on Firefox 12, Google Chrome 19, Opera 11.64, Internet Explorer 9

    This approach checks if the user has not changed cursor's position, you still can do something when you have single click or double click. Hope this solution will help everybody who will need to implement a triple click event listener :)

提交回复
热议问题