功能延迟和取消功能悬停时

时间:2016-02-02 11:18:08

标签: javascript jquery html css

我试图达到以下目的。我想在菜单上盘旋超过3秒后折叠我的菜单。但是当我在3秒之前将鼠标悬停在菜单之外时,它一定不会崩溃。

$("#sidebar").hover(function() {
    if($(this).hasClass("collapsed-by-user")) {
        setTimeout(sidebarCollapse, 3000);
    }
}, function() {
    if($(this).hasClass("collapsed-by-user")) {
        sidebarNotCollapse();
        preventDefault();
    }
});

这是我到目前为止所得到的。 3秒后崩溃正在工作,但如果我在3秒前徘徊,它仍然会崩溃。

知道怎么做吗?

1 个答案:

答案 0 :(得分:3)

如果悬停结束,您需要记住计时器句柄并将其与clearTimeout一起使用,如果它在3秒内完成:

var handle = 0;
var when = 0;
$("#sidebar").hover(function() {
    // Start the timer if we don't have it running already and we have the class
    if(!handle && $(this).hasClass("collapsed-by-user")) {
        handle = setTimeout(function() {
            handle = 0;
            sidebarCollapse();
        }, 3000);
        when = Date.now(); // Remember when it started
    }
}, function() {
    // If we have a handle and it's been less than three seconds,
    // stop the timeout from running by clearing it
    if (handle && Date.now() - when < 3000) {
        clearTimeout(handle);
    }

    // Reset our handle var regardless (for next time)
    handle = 0;
});

请注意,当计时器在callilng handle之前触发时,我们会清除sidebarCollapse

(我不确定你为什么要做那个班级检查,所以我把它留了。)

或按以下Jamiec's comment更新;他是对的,我们真的不需要这样做when检查:

var handle = 0;
$("#sidebar").hover(function() {
    // Start the timer if we don't have it running already and we have the class
    if(!handle && $(this).hasClass("collapsed-by-user")) {
        handle = setTimeout(function() {
            handle = 0;
            sidebarCollapse();
        }, 3000);
    }
}, function() {
    // clearTimeout is a no-op if the timer's already fired
    clearTimeout(handle);
    handle = 0;
});