【问题标题】:jQuery - How can I continue an animation while the mouse hovers over an element?jQuery - 当鼠标悬停在元素上时,如何继续动画?
【发布时间】:2011-01-20 20:19:07
【问题描述】:

我需要一种方法来执行某种“whileonmouseover”功能,以便在鼠标悬停在元素上时继续动画...

例如,给定这个函数:

$(document).ready(function()
{
    function doAlert()
    {
        alert(1);
    }

    $('#button').hover(function()
    {
        doAlert();
    });
});

当鼠标悬停在#button 上时,警报将触发一次。我需要一种方法来在鼠标停留在#button 上方时继续发出警报...

我已经尝试进行某种函数递归来继续警报,直到设置触发器导致它停止:

$(document).ready(function()
{
    var doLoop = true;

    function doAlert()
    {
        if (!doLoop) return;

        alert(1);
        doAlert();
    }

    $('#button').hover(function()
    {
        doAlert();
    }, function()
    {
        doLoop = false;
    });
});

但这失败了。似乎该函数完全忽略了“悬停”中的“doLoop = false”分配。

有什么方法可以做到这一点?

【问题讨论】:

    标签: jquery loops hover


    【解决方案1】:

    我建议设置一个间隔而不是递归,因为假设最终的解决方案不仅仅是警报,而是做一些非阻塞的事情,那么在悬停时递归会很快导致内存占用和无响应。

    类似:

    var hoverInterval;
    
    function doStuff() {
        // Set button's background to a random color
        $("#button").css("background", "#" + Math.floor(Math.random() * 16777215).toString(16));
    }
    
    $(function() {
        $("#button").hover(
            function() {
                // call doStuff every 100 milliseconds
                hoverInterval = setInterval(doStuff, 100);
            },
            function() {
                // stop calling doStuff
                clearInterval(hoverInterval);
            }
        );
    });
    

    【讨论】:

      【解决方案2】:

      我建议将以下部分移到 $(document).ready() 函数的范围之外:

      var doLoop = true;
      
      function doAlert()
      {
          if (!doLoop) return;
      
          alert(1);
          doAlert();
      }
      

      所以试试这个代码吧:

      var doLoop = true;
      
      function doAlert()
      {
          if (!doLoop) return;
      
          alert(1);
          doAlert();
      }
      
      $(document).ready(function()
      {
          $('#button').hover(function()
          {
              doAlert();
          }, function()
          {
              doLoop = false;
          });
      });
      

      【讨论】:

      • 没用。鼠标移开元素后,函数继续循环。 doLoop = false 似乎没有影响。
      • 在这种情况下,从 doAlert 调用 doAlert 会很快导致内存占用和无响应。
      • 我对替代方法持开放态度
      猜你喜欢
      • 2015-02-14
      • 2023-03-26
      • 2016-06-15
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多