jQuery $.animate() multiple elements but only fire

2019-01-05 01:02发布

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

$('.myElems').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++;
    });
});

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?

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?

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

2条回答
男人必须洒脱
2楼-- · 2019-01-05 01:33

You could use when like:

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

http://jsfiddle.net/tyqZq/

Alternate version:

$('.myElems').animate({width: 200}, 200).promise().done(function () {
  console.log('foo');
});
查看更多
该账号已被封号
3楼-- · 2019-01-05 01:42

You can create a variable to block second+ callback...

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

This will only fire once as every subsequent callback will get canceled :)

查看更多
登录 后发表回答