且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.animate() 的回调被调用两次 jquery

更新时间:2023-11-03 22:29:10

animate 为您调用 animate 的集合中的每个元素 调用一次回调:

animate calls its callback once for each element in the set you call animate on:

如果提供,startstepprogresscompletedonefailalways 回调在 每个元素的基础...

If supplied, the start, step, progress, complete, done, fail, and always callbacks are called on a per-element basis...

由于您正在为两个元素(html 元素和 body 元素)设置动画,因此您将获得两个回调.(对于任何想知道为什么 OP 对两个元素进行动画处理的人,这是因为动画在某些浏览器上对 body 起作用,但在 html 上起作用其他浏览器.)

Since you're animating two elements (the html element, and the body element), you're getting two callbacks. (For anyone wondering why the OP is animating two elements, it's because the animation works on body on some browsers but on html on other browsers.)

要在动画完成时获得单个回调,animate 文档指出使用 promise 方法获取动画队列的承诺,然后使用 then 将回调排队:

To get a single callback when the animation is complete, the animate docs point you at using the promise method to get a promise for the animation queue, then using then to queue the callback:

$("html, body").animate(/*...*/)
    .promise().then(function() {
        // Animation complete
    });

(注意:Kevin B 在第一次提出问题时在他的回答中指出了这一点.我没有直到四年后,当我注意到它不见了,添加了它,然后......然后看到了凯文的回答.请给予他应有的爱.我想这是公认的答案,我应该把它留在里面.)

(Note: Kevin B pointed this out in his answer when the question was first asked. I didn't until four years later when I noticed it was missing, added it, and...then saw Kevin's answer. Please give his answer the love it deserves. I figured as this is the accepted answer, I should leave it in.)

这是一个显示单个元素回调和整体完成回调的示例:

Here's an example showing both the individual element callbacks, and the overall completion callback:

jQuery(function($) {

  $("#one, #two").animate({
    marginLeft: "30em"
  }, function() {
    // Called per element
    display("Done animating " + this.id);
  }).promise().then(function() {
    // Called when the animation in total is complete
    display("Done with animation");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

<div id="one">I'm one</div>
<div id="two">I'm two</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>