【问题标题】:Jquery hover with setTimeoutJquery 悬停与 setTimeout
【发布时间】:2011-10-22 13:37:57
【问题描述】:

我有一个水平导航菜单,当用户的鼠标停留在按钮上 1 秒钟时,我想显示一个工具提示。或者换句话说,我希望提示出现的时间有所延迟。当用户将鼠标移开时,工具提示应立即消失。 Stumbleupon 的工具栏是我希望它如何发挥作用的一个示例。

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>

我看了很多教程,不知道为什么我的不起作用。

【问题讨论】:

    标签: jquery navigation hover settimeout


    【解决方案1】:

    如果鼠标在超时发生之前移开,您将立即hide() 它,然后在超时运行后show() 它。

    相反,您应该使用hoverIntent plugin,它会为您执行此操作。

    【讨论】:

      【解决方案2】:

      您有一些语法错误: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();
          }
      );
      

      ps:使用.siblings() 而不是.parent().children()

      【讨论】:

      【解决方案3】:

      首先,您的脚本中存在一些语法错误(如 gion_13 所示)。

      其次,为了确保如果用户在超时完成之前将鼠标移开,工具提示不会错误显示,您需要使用一个变量来存储您的超时,以便您可以在hover 中清除它的handlerOut 参数。

      Working Fiddle.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-11
        相关资源
        最近更新 更多