jQuery .stop()回调问题

时间:2012-04-30 12:34:15

标签: jquery callback

我正在尝试触发动画作为另一个动画的回调。事情是我只希望第二个动画在第一个动画完成时触发,从我读过的是.stop()函数应该如何工作。然而,在我编译的代码中,即使第一个动画没有完成,第二个动画也会触发。

以下是代码:

$(document).ready(function(){
    var angle = 0;

    function arrowRotate() {
        angle +=180;
        $('#arrow img').stop().rotate({
            animateTo: angle,
        }, 100);
    };

    function ToggleOpen(heightValue) {
        $('#information').stop().animate({
            height : heightValue,
        }, 1500, 'easeOutExpo', function(){
            arrowRotate();
        })
    };

    $('#information_container').hover(function(){
        ToggleOpen(500);

    }, function(){
        ToggleOpen(0);
    });

    $('#arrow img').click(function(){
        ToggleOpen(0);
    });

});

我正在使用此第三方插件:http://code.google.com/p/jqueryrotate/

以下是实时实施:http://hopeandpurpose.org

所以基本上我想要完成的是在悬停时提高div的高度,一旦完成,图像就会旋转。问题是即使高度动画没有完成,图像仍然会旋转,并且div会动画回到0。

当我正在查看代码时,似乎我的问题可能是当它徘徊时,它会触发arrowRotate()函数。包含arrowRotate()函数的if函数是否是我最好的解决方案?

1 个答案:

答案 0 :(得分:3)

使用stop(true)停止动画,并清除等待在元素上运行的所有排队动画。

这是一个例子。如果在高度缩小之前将鼠标移开,您将看到该动画未运行,因为它已被mouseleave处理程序中的stop(true)清除。

$("div").hover(function() {
    $(this).stop(true).animate({ width: 300 }, function() {
      $(this).animate({ height: 50 });
    });
  }, function() {
    $(this).stop(true).animate({ width: 50, height: 100 });
  }
);
#test {
  width: 50px;
  height: 100px;
  background-color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">Test</div>