2011-08-08 114 views
1

我有一個水平導航菜單,我想顯示一個工具提示,當用戶的鼠標停留在按鈕上1秒。換句話說,我希望在那裏出現提示時會有延遲。當用戶移開鼠標時,工具提示應立即消失。 Stumbleupon的工具欄是我希望如何運作的例子。jquery懸停setTimeout

的javascript:

$("a.btn").hover(
    function() { 
     var tip = $(this).parent().children(".tip-wrapper"); 
     setTimeout(function{ 
      tip.show(); 
     }, 1000) 
    }, 
    function { 
     var tip = $(this).parent().children(".tip-wrapper"); 
     tip.hide(); 
    } 
); 

HTML:

<th title=""> 
    <a href="#" class="btn"> 
     <span class="person">Firstname Lastname</span> 
    </a> 

    <div class="tip-wrapper"> 
     <div class="tip-border"> 
      <div class="tip"> 
       tool tips go here 
      </div> 
     </div> 
    </div> 
</th> 

我已經看了很多教程,不能找出爲什麼我的不行。

回答

0

如果在超時發生之前鼠標移開,您將立即hide(),然後在超時運行後show()

相反,您應該使用hoverIntent plugin,它會爲您做到這一點。

0

你有一些語法錯誤:function {應該function() {(同樣適用於setTimeout(function{ =>setTimeout(function(){);
我建議使用引用您的超時函數的變量。這樣,如果用戶不會將元素至少停留一秒鐘,則可以停止工具提示的顯示。 :

var timeout; 
$("a.btn").hover(
    function() { 
     var tip = $(this).siblings(".tip-wrapper"); 
     timeout = setTimeout(function(){ 
      tip.show(); 
     }, 1000); 
    }, 
    function() { 
     // prevent the tooltip from appearing 
     clearTimeout(timeout); 
     var tip = $(this).siblings(".tip-wrapper"); 
     tip.hide(); 
    } 
); 

此外,你應該隱藏你在一開始提示。 是一個實時工作示例。

只要你已經在你的項目中使用jquery,我建議你利用它並使用它的動畫功能。這樣一來,你的代碼就變成了:

$("a.btn").hover(
    function(){ 
     $(this).siblings('.tip-wrapper').fadeIn(1000); 
    }, 
    function(){ 
     $(this).siblings('.tip-wrapper').stop().hide();// or fadeOut(); 
    } 
); 

P.S .:使用.siblings(),而不是.parent().children()

+0

或者在使用stop(避免超時變量)時匹配原始意圖,請使用delay(1000).fadeIn(0):http://jsfiddle.net/Lobstrosity/wscUw/ – Lobstrosity

0

首先,在你的腳本(gion_13)指出,一些語法錯誤。其次,爲了確保在超時完成之前用戶將鼠標移開時工具提示不會錯誤顯示,您需要使用變量來存儲超時值,以便您可以在hover' s handlerOut參數。

Working Fiddle