jQuery $ .animate()多个元素,但仅触发一次回调 [英] jQuery $.animate() multiple elements but only fire callback once

查看:469
本文介绍了jQuery $ .animate()多个元素,但仅触发一次回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您选择一个类或元素集合以使用jQuery动画:

If you select a class or collection of elements to animate with jQuery:

$('.myElems').animate({....});

然后还使用回调函数,最终会导致很多不必要的animate()调用.

And then also use the callback function, you end up with a lot of unneccessary animate() calls.

var i=1;
$('.myElems').animate({width:'200px'}, 200, function(){
    //do something else
    $('#someOtherElem').animate({opacity:'1'}, 300, function(){        
        if (i>1) console.log('the '+i+'-th waste of resources just finished wasting your resources');
        i++;
    });
});

可以说这只是错误的代码和/或设计-但我可以做些什么,避免使用回调函数仅使用其中一个避免进行许多animate()调用,并避免执行和拧紧不必要的回调负载我的代码/预期行为?

Arguably this is just bad code and / or design - but is there something I can do that both avoids having many animate() calls with only one of them using the callback, and having a load of unneccessary callbacks executing and screwing with my code / expected behaviour?

理想情况下,我只能够编写一个只能运行一次的一次性"回调,否则也许有一种有效的方法来测试jQuery是否已经在制作动画?

Ideally I'd just be able to code a single 'disposable' callback that will only run once - otherwise perhaps there is an efficient way to test if something is already being animated by jQuery?

示例: http://jsfiddle.net/uzSE6/(警告-这将显示大量警报框).

Example: http://jsfiddle.net/uzSE6/ (warning - this will show a load of alert boxes).

推荐答案

您可以使用 when ,例如:

You could use when like:

$.when($('.myElems').animate({width: 200}, 200)).then(function () {
  console.log('foo');
});

http://jsfiddle.net/tyqZq/

备用版本:

$('.myElems').animate({width: 200}, 200).promise().done(function () {
  console.log('foo');
});

这篇关于jQuery $ .animate()多个元素,但仅触发一次回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆