每个元素的唯一setTimeout计时器?

时间:2012-01-28 02:33:11

标签: jquery

我正在尝试创建一个菜单,其中有以纯文本显示的元素,当您将鼠标悬停在它们上面时,会显示一些字段来编辑纯文本。

您可以在此处查看示例:http://jsfiddle.net/Bx7vX/9/

timer变量是全局声明的,因此当您快速将鼠标悬停在第二个list元素上时,它会清除前一个元素的计时器。但是,当我在函数内部声明计时器(见此处:http://jsfiddle.net/JYavJ/)时,多个元素将正确淡出,但是当您将元素悬停在然后重新打开时,它将不会清除计时器正确。

基本上,我遇到了一个问题,即在单个元素上的鼠标悬停之间保持定时器变量。我已经尝试将定时器变量添加到DOM元素但没有成功。如果有人知道如何解决这个问题,或者更好的方法来完全接近这个菜单风格,我会非常感激。谢谢!

作为参考,这里是在悬停函数之外声明的计时器的代码:

$('.diet_draggable').hover(function() {
var timer;
var current = $(this);

if (current.is(':hover')){
    clearTimeout(timer);
    $(this).children(".static_units").hide();
    $(this).children(".mod_units").show();
}

else if (current.children('.mod_units').children('.list_amount').is(":focus")) {
    current.children('.mod_units').children('.list_amount').blur(function() {
        timer = setTimeout(function() {
            current.children(".mod_units").fadeOut(300);
            current.children(".static_units").fadeIn(300);
        }, 500);
        if (current.is(':hover')) clearTimeout(timer);
    });
}
else {
    timer = setTimeout(function() {
        current.children(".mod_units").fadeOut(300);
        current.children(".static_units").fadeIn(300);
    }, 500);
}
});

1 个答案:

答案 0 :(得分:0)

在这里,这个版本更简单,但可以完全按照您的需要工作:

var dietDraggable = function(element) {
var timer = null;

element.hover(function() {
    clearTimeout(timer);
    $(this).children(".static_units").hide();
    $(this).children(".mod_units").show();
}, function() {
    timer = setTimeout(function() {
        element.children(".mod_units").fadeOut(300);
        element.children(".static_units").fadeIn(300);
    }, 500); 
});

};

$('。diet_draggable')。each(function(){     dietDraggable($(本)); });

关键是我正在使用jQuery悬停函数的两个参数。第二个参数是当您悬停相关元素时发生的情况。另一个关键部分是我在函数dietDraggable中声明了计时器。这确保了为每个元素创建了一个闭包,因此每个元素都有自己的计时器。

要查看它的实际效果:http://jsfiddle.net/VjHcr/2/