如何在JavaScript中收听三次点击? [英] How do I listen for triple clicks in JavaScript?
问题描述
如果是双击:
window.addEventListener("dblclick", function(event) { }, false);
如何捕获三次点击?这适用于Google Chrome中的固定标签。
How can I capture a triple-click? This is for a pinned tab in Google Chrome.
推荐答案
您需要编写自己的三击实现,因为不存在本机事件连续捕获3次点击。幸运的是,现代浏览器有 event.detail
,其中 MDN文档描述为:
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:
在短时间内发生的连续点击次数,递增一个。
A count of consecutive clicks that happened in a short amount of time, incremented by one.
这意味着您只需检查此属性的值,看看它是否 3
:
This means you can simply check the value of this property and see if it is 3
:
window.addEventListener('click', function (evt) {
if (evt.detail === 3) {
alert('triple click!');
}
});
Working demo: http://jsfiddle.net/L6d0p4jo/
如果您需要IE 8的支持,最好的方法是捕获双击,然后点击三次—像这样的东西,例如:
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:
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();
}
});
原因是旧的IE浏览器不会触发两次连续点击事件进行双击。不要忘记使用 attachEvent
代替IE 8的 addEventListener
。
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 attachEvent
in place of addEventListener
for IE 8.
这篇关于如何在JavaScript中收听三次点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!