【问题标题】:$.slideToggle() & $.hover() animation queue issue$.slideToggle() & $.hover() 动画队列问题
【发布时间】:2025-11-24 00:45:02
【问题描述】:

我正在尝试在 jQuery 中设置一个非常基本的悬停动画。鼠标悬停在一个 div 上,主要内容向下滑动,鼠标向上,它向上滑动。

<script type="text/javascript">
    $(function () {
        $('.listItem').hover(function () {
            $(this).find('.errorData').slideToggle('slow');
        });
    });</script>

这段代码运行良好,但明显的问题是,如果您快速进出鼠标,动画会排队。

为了缓解这个问题,我读到 .stop(true) 函数放在 .slideToggle() 之前会停止前一个动画并清除动画队列。所以我尝试了这段代码:

<script type="text/javascript">
    $(function () {
        $('.listItem').hover(function () {
            $(this).find('.errorData').stop(true).slideToggle('slow');
        });
    });</script>

我现在的问题是,这似乎只适用于第一个 mousein 和 mouseout。之后,动画不再触发,也没有任何反应。这是 Google Chrome DEV 频道。

您将鼠标移入和移出的速度似乎加剧了这种情况。

我似乎无法找出问题所在,这个 JSFiddle 有一个工作(并且在我的计算机上中断)示例。

编辑:我怀疑这是 jQuery 1.4.2 中的错误并已提交错误票:http://dev.jquery.com/ticket/6772

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    试试

    .stop(true,true)
    

    或者你可以使用这个hoverIntent plugin

    【讨论】:

    • 这有点用。修复了动画不再工作的问题,但现在它来回跳跃和闪烁,而不是流畅的动画。
    • 是的......真的会。这是因为hover的行为...好吧,你可以试试这个插件...我在这种时候使用它,cherne.net/brian/resources/jquery.hoverIntent.html
    • 该插件几乎为我提供了我想要的功能。修改你的答案,我会这样:)
    • 好吧,我很高兴它对你有所帮助.. :)
    【解决方案2】:
    .stop(true, true)
    

    像冠军一样工作:

      $('.subpage-block').hover(function(){
    
            $('.subpage-block-heading span', this).stop(true,true).fadeToggle('fast');
    
               $('.subpage-block-content', this).stop(true,true).slideToggle();
    
        });
    

    【讨论】:

      【解决方案3】:

      可能会更好?

      $('.listitem').hover(function(){
        if (!$(this).find('.errorData').hasClass('down') &&
            !$(this).find('.errorData').hasClass('up')) {
          $(this).find('.errorData').addClass('down').slideDown('fast', function() {
            $(this).removeClass('down');
          });
        }
      }, function() {
        if (!$(this).find('.errorData').hasClass('up')) {
          $(this).find('.errorData').addClass('up').slideUp('fast', function() {
            $(this).removeClass('up');
          });
        }
      });
      

      这样队列最多有2个,一个是up,一个是down。 在第一个条件下,我们阻止了停留。

      【讨论】:

      • 这如何改进、纠正或改变已接受的答案?