2012-06-03 30 views
1

我有以下代碼。jQuery mouseout和setTimeout

$("#login").mouseout(function() { 
    setTimeout(function() { 
     $("#login").animate({ 
      height: "toggle" 
     }) 
    }, 500); 
}); 

當鼠標離開#login時,它將等待500毫秒,然後它將隱藏該元素。我想要的是,如果鼠標離開元素並在500毫秒內返回,它不會隱藏元素。否則,如果鼠標距元素的「範圍」超過500毫秒,它將調用動畫函數並隱藏該元素。

如果我把這段代碼有

$("#login").mouseover(function() { 
    clearTimeout(t); 
}); 

,我拿鼠標在元素上時,它的關閉動畫完成後,它會再次彈出。

回答

2

聲明一個變量爲setTimeout,這樣就可以使用clearTimeout
(加上解決你的「它會再次彈出」問題)

$("#login") 
    .mouseout(function() { 
     window.t = setTimeout(function() { 
      $("#login").animate({ 
       height: "toggle" 
      }) 
     }, 500); 
    }) 
    .mouseover(function(){ 
     if(window.t){ 
      clearTimeout(window.t); 
      window.t = undefined; 
     }else{ 
      //Do your menu popup thing here 
     } 
    }); 
1

您可以清除超時在mouseentermouseover事件。

var t; 
$("#login").mouseenter(function() { 
    clearTimeout(t); 
}); 
$("#login").mouseout(function() { 
    t = setTimeout(function() { 
     $("#login").animate({ 
      height: "toggle" 
     }) 
    }, 500); 
}); 
+0

這是什麼'?'在最後? –

+0

嗯不知道那是怎麼到的。我編輯了該帖子以將其刪除。 – sachleen