在没有setTimeout的情况下双击时如何防止单击触发

时间:2019-02-19 09:25:44

标签: javascript events event-handling mouseevent dom-events

关于堆栈溢出也有类似的问题,但是我没有找到合适的解决方案。

在双击的情况下,我不希望触发单击功能,因此我想在没有jQuery和setTimeout的情况下将其存档。

这可以通过setTimeout实现,但是在延迟时间内阻止了鼠标移动事件。

代码:https://codesandbox.io/s/vnrk3xk115

mouseDown = (e) => {
    // Case 1
    // In the case of double clicks, a single click will still trigger. 
    if (e.detail === 1) {
      console.log('Single Click');
    } else if (e.detail === 2) {
      console.log('Double Click');
    }

    // Case 2
    // In the case, I can't use mouse move for 250ms
    let timeoutID = null;

    if (!timeoutID) {
      timeoutID = setTimeout(() => {
        console.log('Single Click');
        timeoutID = null;
      }, 250);
    } else {
      timeoutID = clearTimeout(timeoutID);
      console.log('Double Click');
    }
  }

  mouseMove = () => {
    // Mouse move is blocked for 250ms
  } 

1 个答案:

答案 0 :(得分:0)

我认为setTimeout是必需的,但是您可以以其他方式使用它。 将您的功能标记为单击,然后使用超时将其重置以避免双击。

请查看以下内容: https://codesandbox.io/s/73n357xx36

如果我的想法正确,那么它应该适合您的需求。