【问题标题】:Grouping elements and run animations separately将元素分组并分别运行动画
【发布时间】:2015-04-13 21:50:08
【问题描述】:

我正在尝试实现 $.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 中淡入...

I did an example here.

提前致谢。

【问题讨论】:

    标签: jquery


    【解决方案1】:

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

    Working fiddle

    jQuery 还允许您将这些与 $.when 聚合,这样您就可以一次等待多个值。

    但为什么我的代码不起作用?

    您没有定义静态$.groups。你只把它放在原型上。所以第二行和第三行的用法是行不通的。此外,您还有一个 while 循环,由于 JS 在此上下文中是单线程的,因此最终会无限运行。

    【讨论】:

    • 哇!我不知道...重新发明轮子太难了kkk ..非常感谢!
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    相关资源
    最近更新 更多