Skip to content

table 行双击事件和单击事件同时存在 执行双击事件总会连单击事件 一起执行 #1918

Answered by Sight-wcg
aimu2000 asked this question in 问答
Discussion options

You must be logged in to vote

在JavaScript中,如果双击事件(dblclick)和单击事件(click)同时绑定在同一个元素上,当你双击元素时,两个事件都将被触发。为了区分两个事件,你可以使用 setTimeout 函数来添加一定的延迟。
你可以使用一个标识变量来检查是否双击,如下所示:

let clickTimer = null;
let isDoubleClick = false;
element.addEventListener('click', function(e) {
  if(clickTimer === null) {
    clickTimer = setTimeout(function() {
      clickTimer = null;
      if(!isDoubleClick) {
        console.log('单击事件!')
      }
    }, 200);
  }
});
element.addEventListener('dblclick', function(e) {
  clearTimeout(clickTimer);
  clickTimer = null;
  isDoubleClick = true;
  console.log('双击事件!')
});

这段代码在每次点击时都设置了一个延迟,如果在设定的时间(这里是200毫秒)内双击事件被触发,就会清除计时器和单击事件。这可以确保两个事件不会同时发生。
注意,你可能需要根据你的具体需求调整延迟的时间。在一些情况下,可能还需要对实现的细节进行稍微的调整。
希望这可以帮助你…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@Cuixq123
Comment options

@Sight-wcg
Comment options

Answer selected by aimu2000
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
问答
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #1917 on May 19, 2024 08:01.