【问题标题】:jQuery $.animate() multiple elements but only fire callback oncejQuery $.animate() 多个元素但只触发一次回调
【发布时间】:2012-02-06 06:32:42
【问题描述】:

如果您选择一个类或元素集合以使用 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/(警告 - 这将显示大量警报框)。

【问题讨论】:

  • 在文件范围内或animate() 可访问的某个地方定义一个标志变量。在$("#someOtherElem').animate() 调用之前检查它并将其设置在它的主体中,以便下次不会调用$("#someOtherElem').animate()

标签: jquery jquery-animate jquery-callback


【解决方案1】:

你可以使用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');
});

【讨论】:

  • 我喜欢这个。我非常喜欢这个。我不知道这些功能,这很有帮助:)
  • +1 我发现它对$('html, body').animate(...)很有用
【解决方案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++;
        }
    });
});

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

【讨论】:

  • 我建议使用与i 不同的变量名称,这很常见,很可能会被意外覆盖,并将其设置为truefalse 以更清晰。
  • ^ 当然,但我使用 i 因为它已经在示例代码中可用,我只是稍微调整了一下使用它。从清晰的角度来看,将callbackdone 设置为布尔值会更有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-14
  • 2017-09-14
  • 2016-04-20
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多