gpt4 book ai didi

javascript - jquery 使用多个 setTimeouts

转载 作者:行者123 更新时间:2023-12-01 02:13:26 26 4
gpt4 key购买 nike

我目前正在创建一个包含一些动态内容的网站,以便每当用户将鼠标悬停在标签上时,标签就会展开以显示更多信息,然后在特定时间后,标签将再次折叠,除非用户将鼠标悬停在标签上在这种情况下,超时将重置。我已经开发了针对 1 个标签执行此操作的代码,但我现在想开发它以针对多个标签执行此操作。

我遇到的问题是,我正在全局定义计时器的变量,因此它可以用于这两个事件,但当我有多个标签时,这将不起作用。

我无法想象如何为多个标签实现此目的,有人知道我该如何做到这一点吗?

这是到目前为止我的代码...

    var timer;


$('.label').mouseenter(function(){

clearTimeout(timer);

$('#' + this.id + ' div').slideDown('slow');

});


$('.label').mouseleave(function(){

var temp = $('#' + this.id + ' div');

timer = setTimeout(function() {
temp.stop().slideUp('slow');
}, 2000);

});

预先感谢您的帮助。

最佳答案

您可以维护一系列计时器,例如

var timer = [];


$('.label').mouseenter(function(){

clearTimeout(timer[$(this).index()]);

$('#' + this.id + ' div').slideDown('slow');

});


$('.label').mouseleave(function(){

var temp = $('#' + this.id + ' div');

timer[$(this).index()] = setTimeout(function() {
temp.stop().slideUp('slow');
}, 2000);

});

您还可以使用 .hover 通过更清晰的语法来实现此目的喜欢

var timer = [];

$('.label').hover(function(){

clearTimeout(timer[$(this).index()]);

$('#' + this.id + ' div').slideDown('slow');

},function(){
var temp = $('#' + this.id + ' div');

timer[$(this).index()] = setTimeout(function() {
temp.stop().slideUp('slow');
}, 2000);

});

关于javascript - jquery 使用多个 setTimeouts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10915141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com