2011-08-08 65 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