settimeout没有被清除

时间:2012-12-17 17:54:58

标签: javascript jquery

我要做的是,当页面加载一个框后3秒钟出现,如果没有任何反应,它会在3秒后被部分隐藏。现在,如果光标进入该框,则清除超时,并且在我清除超时时广告不会被隐藏。

问题是当鼠标离开并再次进入时,之前的超时仍然存在。虽然我试图清除超时但它仍然隐藏了盒子。可能是什么问题?

请参阅我的代码:(JSfiddle link:http://jsfiddle.net/aK9nB/

var pstimer;

$(document).ready(function(){
    setTimeout(function(){
        showps();
        pstimer = setTimeout(function() {
                hideps();
        }, 3000);
    }, 3000);
});

$('#psclose').on('click', function(){
    $('#postsearch-container').hide();
});

$("#postsearch-container").hover(
    function () {
        console.log("enter");
        clearTimeout(pstimer);
        console.log("cleartimeout");
        showps();
    }, 
    function () {   
        console.log("leave");
        clearTimeout(pstimer);
        var pstimer = setTimeout(function(){
            hideps();
    } , 3000);
});

function showps() { 
    $("#postsearch-container").stop();
    $('#postsearch-container').animate({
        bottom: '0'
    }, 'slow');
}

function hideps() {
    $('#postsearch-container').animate({
        bottom: '-115'
    }, 'slow');
}

2 个答案:

答案 0 :(得分:2)

$("#postsearch-container").hover(
    function () {
        console.log("enter");
        clearTimeout(pstimer);
        console.log("cleartimeout");
        showps();
    }, 
    function () {   
        console.log("leave");
        clearTimeout(pstimer);
        pstimer = setTimeout(function(){ // remove the "var" 
            hideps();
        } , 3000);
    }
);

答案 1 :(得分:2)

尝试删除pstimer前面的 var

    function () {   
        console.log("leave");
        clearTimeout(pstimer);
        /* var */ pstimer = setTimeout(function(){
            hideps();
        } , 3000);
    }

using var定义了一个新的本地变量,该变量与您想要的pstimer共享名称,但仅在此函数调用中可用。函数完成后,本地var将被销毁。

相关问题