如何等到jQuery效果完成?

时间:2021-10-04 19:42:00

How can I wait until an animation is finished in jQuery?

我怎么能等到jQuery中的动画结束?

function foo() {
  $("#element").fadeOut();
}

I need the .fadeOut() to complete before foo() returns because the calling code expects the DOM to be free of #element.

我需要在foo()返回之前完成.fadeOut(),因为调用代码期望DOM没有#element。

5 个解决方案

#1


0  

All jQuery animation functions have a complete callback. Because they are asyncronous you can't wait for them, you have to use callbacks.

所有jQuery动画函数都有完整的回调。因为它们是异步的,所以你不能等待它们,你必须使用回调。

function foo() {
    $("#element").fadeOut(function() {
        // finished
    });
}

#2


0  

jQuery defines fadeout as: .fadeOut( [duration ] [, complete ] ), so using a callback should just work fine.

jQuery将fadeout定义为:.fadeOut([duration] [,complete]),因此使用回调应该可以正常工作。

complete Type: Function() A function to call once the animation is complete, called once per matched element.

complete类型:Function()动画完成后调用的函数,每个匹配元素调用一次。

#3


0  

Use a callback function for this

为此使用回调函数

function foo() {
  $("#element").fadeOut('slow', function(){
     // called when the element finishes fading out
  });
}

#4


0  

You can't prevent foo from returning before the animation finishes. You need to use the callback or promise/deferred pattern. Here's how a callback could work:

在动画结束之前,您无法阻止foo返回。您需要使用回调或承诺/延迟模式。以下是回调的工作原理:

function bar() {
    foo(function() {
        // stuff to execute after foo()
    });
}

function foo(callback) {
    $("#element").fadeOut('speed', callback);
}

#5


0  

$('#element').fadeOut(1000, function() {
  // after 1 second do something

});

#1


0  

All jQuery animation functions have a complete callback. Because they are asyncronous you can't wait for them, you have to use callbacks.

所有jQuery动画函数都有完整的回调。因为它们是异步的,所以你不能等待它们,你必须使用回调。

function foo() {
    $("#element").fadeOut(function() {
        // finished
    });
}

#2


0  

jQuery defines fadeout as: .fadeOut( [duration ] [, complete ] ), so using a callback should just work fine.

jQuery将fadeout定义为:.fadeOut([duration] [,complete]),因此使用回调应该可以正常工作。

complete Type: Function() A function to call once the animation is complete, called once per matched element.

complete类型:Function()动画完成后调用的函数,每个匹配元素调用一次。

#3


0  

Use a callback function for this

为此使用回调函数

function foo() {
  $("#element").fadeOut('slow', function(){
     // called when the element finishes fading out
  });
}

#4


0  

You can't prevent foo from returning before the animation finishes. You need to use the callback or promise/deferred pattern. Here's how a callback could work:

在动画结束之前,您无法阻止foo返回。您需要使用回调或承诺/延迟模式。以下是回调的工作原理:

function bar() {
    foo(function() {
        // stuff to execute after foo()
    });
}

function foo(callback) {
    $("#element").fadeOut('speed', callback);
}

#5


0  

$('#element').fadeOut(1000, function() {
  // after 1 second do something

});