运用setTimeout完成双击事宜
比方,如许:
let div = document.getElementById("div");
doubleClick(div, function (event) {
console.log('双击')
})
function doubleClick(ele, fn) { // 省略参数合法性的推断
let event = new Event("doubleClick"); // 自定义双击事宜(能够运用CustomEvent照顾数据)
// 双击事宜监听
ele.addEventListener("doubleClick", function (event) {
fn(event);
});
// 双击事宜触发
let timeout;
let clicked = false; // 是不是已点击过一次
ele.addEventListener("click", function () {
if (clicked) {
clicked = false;
if (timeout) {
clearTimeout(timeout);
}
ele.dispatchEvent(event); // 事宜分发
} else {
clicked = true;
timeout = setTimeout(function () {
clicked = false;
}, 400);
}
});
}
运用数组完成双击事宜或n击事宜
灵感来自于Android体系多击触发彩蛋的源码
用前端的体式格局完成长如许:
let div = document.getElementById("div");
multiClick(div, function (event) {
console.log('双击')
}, 2)
function multiClick(ele, fn, clickNum) { // 省略参数合法性的推断
let event = new Event("multiClick"); // 建立n击事宜(能够运用CustomEvent照顾数据)
let hits = [];
// n击事宜监听
ele.addEventListener("multiClick", function (event) {
fn(event);
});
// n击事宜触发
ele.addEventListener("click", function () {
let now = new Date().getTime();
hits.push(now);
if (hits.length > 1) {
if (hits[0] + 500 > now) {
if (hits.length === clickNum) {
hits = [];
ele.dispatchEvent(event); // 事宜分发
}
} else {
hits.shift();
}
}
});
}