如果您选择要使用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/(警告 - 这将显示大量警报框)。
答案 0 :(得分:104)
您可以使用when
之类的:
$.when($('.myElems').animate({width: 200}, 200)).then(function () {
console.log('foo');
});
替代版本:
$('.myElems').animate({width: 200}, 200).promise().done(function () {
console.log('foo');
});
答案 1 :(得分:2)
您可以创建一个变量来阻止第二个+回调...
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++;
}
});
});
这只会触发一次,因为每个后续回调都会被取消:)