如何在 JavaScript 中监听三次点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6480060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:57:02  来源:igfitidea点击:

How do I listen for triple clicks in JavaScript?

javascriptgoogle-chromedom-events

提问by Sam-Bo

If this is for a double-click:

如果这是双击:

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

How can I capture a triple-click? This is for a pinned tab in Google Chrome.

如何捕捉三次点击?这是针对 Google Chrome 中的固定选项卡。

回答by Andy E

You need to write your own triple-click implementation because no native event exists to capture 3 clicks in a row. Fortunately, modern browsers have event.detail, which the MDN documentation describes as:

您需要编写自己的三次点击实现,因为不存在可连续捕获 3 次点击的本机事件。幸运的是,现代浏览器具有event.detailMDN 文档将其描述为

A count of consecutive clicks that happened in a short amount of time, incremented by one.

短时间内发生的连续点击次数,递增 1。

This means you can simply check the value of this property and see if it is 3:

这意味着您可以简单地检查此属性的值并查看它是否为3

window.addEventListener('click', function (evt) {
    if (evt.detail === 3) {
        alert('triple click!');
    }
});

Working demo: http://jsfiddle.net/L6d0p4jo/

工作演示:http: //jsfiddle.net/L6d0p4jo/



If you need support for IE 8, the best approach is to capture a double-click, followed by a triple-click — something like this, for example:

如果您需要对 IE 8 的支持,最好的方法是捕获双击,然后是三次单击,例如:

var timer,          // timer required to reset
    timeout = 200;  // timer reset in ms

window.addEventListener("dblclick", function (evt) {
    timer = setTimeout(function () {
        timer = null;
    }, timeout);
});
window.addEventListener("click", function (evt) {
    if (timer) {
        clearTimeout(timer);
        timer = null;
        executeTripleClickFunction();
    }
});

Working demo: http://jsfiddle.net/YDFLV/

工作演示:http: //jsfiddle.net/YDFLV/

The reason for this is that old IE browsers will not fire two consecutive click events for a double click. Don't forget to use attachEventin place of addEventListenerfor IE 8.

这样做的原因是旧的 IE 浏览器不会为双击触发两个连续的单击事件。不要忘记使用attachEvent代替addEventListenerIE 8。

回答by Artem Oboturov

Since DOM Level 2 you could use mouse click handler and check the detailparameter of event which should be interpreted as:

从 DOM 级别 2 开始,您可以使用鼠标单击处理程序并检查detail应解释为的事件参数:

The detail attribute inherited from UIEvent indicates the number of times a mouse button has been pressed and released over the same screen location during a user action. The attribute value is 1 when the user begins this action and increments by 1 for each full sequence of pressing and releasing. If the user moves the mouse between the mousedown and mouseup the value will be set to 0, indicating that no click is occurring.

从 UIEvent 继承的 detail 属性指示在用户操作期间在同一屏幕位置上按下和释放鼠标按钮的次数。当用户开始这个动作时,该属性值为 1,并且对于每个完整的按下和释放序列递增 1。如果用户在 mousedown 和 mouseup 之间移动鼠标,该值将设置为 0,表示没有发生单击。

So the value of detail === 3will give you the triple-click event.

所以值detail === 3会给你三次点击事件。

More information in specification at http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent.

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent规范中的更多信息。

Thanks to @Nayuki https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail- a DOM3 extension which is WIP https://w3c.github.io/uievents/

感谢@Nayuki https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail- 一个 DOM3 扩展是 WIP https://w3c.github.io/uievents/

回答by Deliaz

Here is the real Triple click event, which triggers only when all of three clicks fired with equal interval.

这是真正的 Triple click 事件,它仅在所有 3 次点击以相等的间隔触发时触发。

// Default settings
var minClickInterval = 100,
    maxClickInterval = 500,
    minPercentThird = 85.0,
    maxPercentThird = 130.0;

// Runtime
var hasOne = false,
    hasTwo = false,
    time = [0, 0, 0],
    diff = [0, 0];

$('#btn').on('click', function() {
    var now = Date.now();
    
    // Clear runtime after timeout fot the 2nd click
    if (time[1] && now - time[1] >= maxClickInterval) {
        clearRuntime();
    }
    // Clear runtime after timeout fot the 3rd click
    if (time[0] && time[1] && now - time[0] >= maxClickInterval) {
        clearRuntime();
    }
    
    // Catch the third click
    if (hasTwo) {
        time[2] = Date.now();
        diff[1] = time[2] - time[1];
        
        var deltaPercent = 100.0 * (diff[1] / diff[0]);
        
        if (deltaPercent >= minPercentThird && deltaPercent <= maxPercentThird) {
            alert("Triple Click!");
        }
        clearRuntime();
    }
    
    // Catch the first click
    else if (!hasOne) {
        hasOne = true;
        time[0] = Date.now();
    }
    
    // Catch the second click
    else if (hasOne) {
        time[1] = Date.now();
        diff[0] = time[1] - time[0];
        
        (diff[0] >= minClickInterval && diff[0] <= maxClickInterval) ?
            hasTwo = true : clearRuntime();
    }  
});

var clearRuntime = function() {
    hasOne = false;
    hasTwo = false;
    time[0] = 0;
    time[1] = 0;
    time[2] = 0;
    diff[0] = 0;
    diff[1] = 0;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click button three times with equal interval
<button id="btn">Click me</button>

Also, I wrote jquery plugin TrplClick, which enables 'trplclick' event

另外,我编写了jquery 插件 TrplClick,它启用了 'trplclick' 事件

回答by Bernhard

it's very simple if you do it right, and you can even catch single, double, triple, ... clicks as you like. plain javascript, customizable click delay (timeout):

如果操作得当,这将非常简单,您甚至可以随心所欲地捕捉单、双、三、...点击。纯javascript,可自定义的点击延迟(超时):

var clicks = 0;
var timer, timeout = 350; // time between each click

var doubleClick = function(e) {
  console.log('doubleClick');
}

var tripleClick = function(e) {
  console.log('tripleClick');
}

// click timer
yourcontainer.addEventListener('click', function(e) {
  clearTimeout(timer);
  clicks++;
  var evt = e;
  timer = setTimeout(function() {
    if(clicks==2) doubleClick(evt);
    if(clicks==3) tripleClick(evt);
    clicks = 0;
  }, timeout);
});

回答by Hyman M

pseudo-code:

伪代码:

var clicks = 0

onclick:
clicks++;
setTimer(resetClicksToZero);
if clicks == 3: tripleclickdetected(); clicks = 0;

回答by micnic

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:

我正在开发一个 javascript 代码编辑器,我不得不听三次点击,这是适用于大多数浏览器的解决方案:

// 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

在 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 :)

这种方法检查用户是否没有改变光标的位置,当你单击或双击时你仍然可以做一些事情。希望这个解决方案能帮助每个需要实现三次点击事件监听器的人:)