我有一系列的父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);
});
最佳答案
您应该为每个 .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/