2012-12-17 61 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共享名稱,但僅在此函數調用中可用。當函數完成時,局部變量被銷燬。