40

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

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

然后还使用回调函数,你最终会得到很多不必要的animate()调用。

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()只有一个调用使用回调进行多次调用,以及执行大量不必要的回调并搞砸我的代码/预期的行为?

理想情况下,我只能编写一个只运行一次的“一次性”回调 - 否则也许有一种有效的方法来测试是否已经被 jQuery 动画化了?

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

4

2 回答 2

107

你可以when像这样使用:

$.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');
});
于 2012-01-09T18:50:07.427 回答
2

您可以创建一个变量来阻止 second+ 回调...

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++;
        }
    });
});

这只会触发一次,因为每个后续回调都将被取消:)

于 2012-01-09T18:30:31.850 回答