上次在 react 中使用单双击事件时遇到了问题,当时写了一个单双击解决方案。
今天在 github 上看到了一个更优雅的方案,利用了闭包:
<div id="thing">Click me</div>
var thingEl = document.getElementById('thing');
thingEl.addEventListener(
'click',
getClickHandler(
function () {
console.log('click');
},
function () {
console.log('dblclick');
}
)
);
function getClickHandler(onClick, onDblClick, delay) {
var timeoutID = null;
delay = delay || 250;
return function (event) {
if (!timeoutID) {
timeoutID = setTimeout(function () {
onClick(event);
timeoutID = null
}, delay);
} else {
timeoutID = clearTimeout(timeoutID);
onDblClick(event);
}
};
}