如何缩短我的jQuery片段?

时间:2013-04-11 23:15:25

标签: jquery

我已经尝试了很多来缩短我的片段,但没有什么对我有用。

这是:

var logoTitle = $(".logoTitle");

logoTitle.children(".char3, .char4").delay(300).each(function() {
    $(this).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");
});

logoTitle.children(".char2, .char5").delay(600).each(function() {
    $(this).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");
});

logoTitle.children(".char1, .char6").delay(900).each(function() {
    $(this).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");
});

如何缩短效率并提高效率?

4 个答案:

答案 0 :(得分:0)

如果您希望立即运行,就像您的原始脚本一样:

(function animateLogoChildren(theChildren, theDelay){
    var logoTitle = $(".logoTitle");

    logoTitle.children(theChildren).delay(theDelay).each(function() {
        $(this).animate({
            'margin-top':'0', 
            'opacity':'1'
        }, 330, "easeOutQuart");
    });
})(".char3, .char4", 300);

如果您希望在通话中运行:

function animateLogoChildren(theChildren, theDelay){
    var logoTitle = $(".logoTitle");

    logoTitle.children(theChildren).delay(theDelay).each(function() {
        $(this).animate({
            'margin-top':'0', 
            'opacity':'1'
        }, 330, "easeOutQuart");
    });
}

animateLogoChildren(".char3, .char4", 300);
animateLogoChildren(".char2, .char5", 600);
animateLogoChildren(".char1, .char6", 900);

考虑到我如何清理代码,第二个很可能是你正在寻找的东西。希望这有帮助!

答案 1 :(得分:0)

您不需要每个功能。如果您下载有效的定义,这将使其更“高效”。但速度明智,你无能为力。

var logoTitle = $(".logoTitle");

logoTitle.children(".char3, .char4").delay(300).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");
logoTitle.children(".char2, .char5").delay(600).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");
logoTitle.children(".char1, .char6").delay(900).animate({
        'margin-top':'0', 
        'opacity':'1'
    }, 330, "easeOutQuart");

答案 2 :(得分:0)

我希望制作一个自定义动画功能,以允许重用代码,例如:

var logoTitle = $(".logoTitle");

$.fn.myAnimate = function(delayTime) { 
    return $(this).delay(delayTime).each(function(){
        $(this).animate({
            'margin-top':'0', 
            'opacity':'1'
        }, 330, "easeOutQuart");
    })
}

logoTitle.children(".char3, .char4").myAnimate(300);
logoTitle.children(".char2, .char5").myAnimate(600);
logoTitle.children(".char1, .char6").myAnimate(900);

答案 3 :(得分:0)

试试这个:

var logoTitle = $(".logoTitle");

function animate_kids(kids, delay) {
    kids.delay(delay).animate({
            'margin-top': 0,
            'opacity': 1
        }, 330, "easeOutQuart"); 
    });
};

animate_kids(logoTitle.children(".char3, .char4"), 300);
animate_kids(logoTitle.children(".char2, .char5"), 600);
animate_kids(logoTitle.children(".char1, .char6"), 900);

如果您有任何疑问,请与我们联系。祝好运! :)