2012-12-17 62 views
0

我想要做的是,当页面加载一个盒子出现3秒后,如果没有任何反应,它会在3秒后部分隐藏。现在,如果光标进入框中,超时被清除,并且由于我正在清除超时,所以广告不会被隐藏。settimeout没有得到清除

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

见我的代码:(的jsfiddle链接: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'); 
} 
+6

'var pstimer'正在声明一个新的函数范围变量,它不能从该范围之外访问。这是**不**设置您声明的全局。 – Shmiddty

回答

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); 
    } 
); 
+0

非常感谢。很快就会接受答案。 – vivek

2

尝试pstimer前去除VAR

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

使用var定义了一个新的局部变量,它与您想要的pstimer共享名称,但仅在此函数调用中可用。当函数完成时,局部变量被销毁。