当两个事件绑定在同一个 dom 上时,只会触发单击事件
使用延迟来解决,代码如下:
// html<div id="a">单击 or 双击</div>// jsconst dom = document.getElementById('a');// 单击事件dom.onclick = function () {if (window.timer) {clearTimeout(window.timer);window.timer = null;}window.timer = setTimeout(function () {// TODO: 业务代码alert('单击');}, 200);};// 双击事件dom.ondblclick = function () {if (window.timer) {clearTimeout(window.timer);window.timer = null;}// TODO: 业务代码alert('双击');}
使用计数+延迟解决,代码如下:
不使用 dblclick 事件,只使用 click。在单位时间延迟内点击 2次 则为双击,否则为单击
// html<div id="b">单击 or 双击</div>// jsconst dom2 = document.getElementById('b');let count = 0;dom2.onclick = function () {count ++;window.timer2 = setTimeout(function () {if (count === 1) {// TODO: 业务代码alert('单击');count = 0;return;}// TODO: 双击业务代码alert('双击');count = 0;clearTimeout(window.timer2);window.timer2 = null;}, 200);}
