bistukey 2019-06-26
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); } }); }
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(); } } }); }