我正在尝试实现 $.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);
它应该在 group(0) 的第一个 div 中淡入淡出,当动画完成时,在 group(0) 的第二个 div 中淡入淡出...
提前致谢。
最佳答案
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
。你只需将它放在原型(prototype)上。所以第二行和第三行的用法不起作用。另外,你还有一个 while 循环,它最终会无限运行,因为 JS 在这种情况下是单线程的。
关于jquery - 对元素进行分组并单独运行动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606688/