分组元素并分别运行动画
我正在尝试实现$ .groups()。
主要思想是:如果我有一个依赖于另一个元素的元素,我将对它们进行分组,并且只有当其他组元素停止运行时,才能启动该元素的动画。
我懂了:
/* mini-plugin */ var groups = []; $.fn.extend({ group: function (key, selector) { if (key < groups.length) { selector && groups[key].add(selector); } else if (key == groups.length) { groups.push( $(this).add( (selector||this )) ); } groups[key] && (function(){ while (groups[key].is(":animated")); })(); return groups[key]; } });
但是,它不能按我的意愿工作(我不知道为什么!)
/* testing */ $("div").hide(); $("#div1").group(0).fadeIn(2000); $.group(0, "#div2").fadeIn(3000); $.group(0, "#div3").fadeIn(4000);
它应该淡入组(0)的第一个div并且当完成动画时,fadeIn组的第二个div(0)…
我在这里做了一个例子。
提前致谢。
jQuery已经为你实现了这个! 很酷,对吗?
对于排队异步操作(如动画和ajax请求) – jquery使用promises 。 您在纯jQuery示例中的代码如下所示:
// calling `.promise` on an element returns a promise for when its animations are over $("#div1").fadeIn(1000).promise().then(function(){ // .then chains promises, the code here only executes after the // .fadeIn(1000) on #div1 is done // returning a promise from a promise will wait for it when continuing // a chain return $("#div2").fadeIn(1000).promise(); }).then(function(){ // because of the return value, this only runs after div2 is done // animating return $("#div3").fadeIn(1000).promise(); });
工作小提琴
jQuery还允许您使用$.when
聚合这些,以便您可以一次等待多个值。
但为什么我的代码不起作用?
您没有定义静态$.groups
。 你只把它放在原型上。 所以第二和第三行使用不起作用。 此外,你有一个while
循环,最终会无限运行,因为JS在这种情况下是单线程的。