jQuery 鼠标悬停/鼠标悬停延迟,多个元素

标签 jquery delay mouseover mouseout

我有一系列的父div(共享同一个类),每个div包含一个子元素。 当我将鼠标悬停在父级上时,我想为其子级添加一个类。 当我鼠标移开时,我想以 500 毫秒的延迟删除该类。

我认为 setTimeout 是解决延迟的方法。 为了防止 mouseout 在我实际返回父级后触发removeClass,我想到了使用clearTimeout。 问题是我无法仅当新悬停的父级与前一个相同时触发clearTimeout。这样做的结果是,如果我在 500 毫秒内从父级 A 悬停到父级 B,则父级 A 上不会触发removeClass(正如我实际上希望的那样)。

我希望这是有道理的。非常感谢任何帮助!

var timer

$('.parent')
  .mouseover(function() {
    //clearTimeout(timer)
    $(this).children('.child').addClass('red');
  })
  .mouseleave(function() {
    that = this
    timer = setTimeout(function() {
      $(that).children('.child').removeClass('red');
    }, 500);
  });

https://jsfiddle.net/andinse/1wnp82nm/

最佳答案

您应该为每个 .parent 元素设置特定的超时,并将相关上下文绑定(bind)到 setTimeout 回调,例如使用 bind() 来避免变量那个关闭问题:

-DEMO-

$('.parent')
  .mouseover(function() {
    clearTimeout(this.timer)
    $(this).children('.child').addClass('red');
  })
  .mouseleave(function() {
    this.timer = setTimeout(function() {
      $(this).children('.child').removeClass('red');
    }.bind(this), 500);
  });

关于jQuery 鼠标悬停/鼠标悬停延迟,多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39643808/

相关文章:

javascript - 根据 url 具有自定义内容的静态页面

javascript - 使用回调函数 Javascript 延迟/重复打印屏幕数组元素

javascript - 将鼠标悬停在切片上时更改 d3.js 饼图标签的颜色?

javascript - 使用JQuery,如何实现鼠标进入一次就播放视频,鼠标进入两次就暂停视频?

jquery - 如何避免文件上传时的 CORS 预检请求?

javascript - 获取html数据属性字符串甚至其值 bool 值

delphi - 在执行 ShellExecute 之前等待?

swift - 通知延迟?

javascript - 如何首先找到鼠标点击,如果没有点击,然后再寻找鼠标悬停

jquery - JQGrid editOptions 值不起作用