【问题标题】:Show and hide content on hover with delay延迟悬停时显示和隐藏内容
【发布时间】:2015-12-21 09:23:51
【问题描述】:

我需要做一件事。 我在网页上有元素。当用户将鼠标悬停在此项目上时,我需要例如显示警报。但有延迟:当用户将鼠标悬停在项目上并且一秒钟后鼠标仍在项目上时,将显示警报。我可以做到,但是当鼠标离开同一个项目时我想做同样的事情(当鼠标离开项目并且一秒钟后仍然在项目之外)。现在我使用此代码,但它当然不适用于离开

$('.test').hover(function(){
  mytimeout = setTimeout(function(){
    alert("enter");
  }, 1000);
}, function(){
     clearTimeout(mytimeout);
});


$('.test').mouseleave(function() {
  alert("escape");
});

当然,我不会将它与警报一起使用;) 我不知道该怎么做。悬停悬停?还是用别的东西? 谢谢你的帮助,对不起我的英语。

【问题讨论】:

    标签: javascript jquery hover


    【解决方案1】:

    您需要在两个块中超时,进入/离开,如下所示:

    var $demo = $("#demo");
    var timer;
    
    $('.test').hover(function() {
        //Clear timeout just in case you hover-in again within the time specified in hover-out
        clearTimeout(timer);
        timer = setTimeout(function() {
            $demo.text("enter");
        }, 1000);
    }, function() {
        //Clear the timeout set in hover-in
        clearTimeout(timer);
        timer = setTimeout(function() {
            $demo.text("exit");
        }, 1000);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <button class="test">Hover me!</button>
    
    <div id="demo"></div>

    【讨论】:

    • 这正是我所需要的。谢谢。
    【解决方案2】:

    你几乎拥有它。 jquery 悬停函数有两个参数,一个 onHoverStart(或 onMouseOver)处理程序和一个 onHoverStop(或 onMouseLeave)处理程序。您只需要将警报添加到 onHoverStop 处理程序。

    $('#test').hover(function(){
      setTimeout(function(){
        alert("enter");
      }, 1000);
    }, function(){
      setTimeout(function(){
        alert("escape");
      }, 1000);
    });
    

    【讨论】:

      【解决方案3】:

      Working fiddle.

      如果您愿意,您可以在mouseleave 中遵循相同的想法,您只需在hover 事件上清除计时器timer_mouseleave

      var timer_mouseleave;
      
      $('.test').hover(function(){
            clearTimeout(timer_mouseleave);
      
            mytimeout = setTimeout(function(){
              alert("enter");
            }, 2000);
      }, function(){
           clearTimeout(mytimeout);
      });
      
      $('.test').mouseleave(function() {
            timer_mouseleave = setTimeout(function(){
              alert("escape");
            }, 2000);
      });
      

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        试试这个。只需要在每个悬停事件上重置超时。

        (function(){
                var mytimeout = null;
                $('.test').hover(function(){
                    clearTimeout(mytimeout);
                    mytimeout = setTimeout(function(){
                        alert("enter");
                    },1000);
                });
            })();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-27
          • 1970-01-01
          • 2017-07-18
          • 1970-01-01
          相关资源
          最近更新 更多