如何/可能?结合这些变量和animate()函数?

时间:2014-11-15 20:54:30

标签: jquery variables colors jquery-animate minify

我刚开始编写自己的jQuery,并获得了一些代码片段的帮助,这些代码可以根据我的需要运行(在jquery-color.js plugin的帮助下为颜色设置动画,然后循环/循环它们连续地):

var c = 0;
setInterval(function () {
    var colors = ['#de7056', '#4ec67f']
    if (c > colors.length - 1) c = 0;
    $("#neck").animate({
        backgroundColor: colors[c++]
    }, 1000);
}, 5000);

但现在我已多次使用此片段(var c1,var c2等)更改多个元素的颜色,背景颜色,svgFill和svgStroke(在svg animate plugins的帮助下)(#color -change1,#color-change2等)我想知道是否有组合所有片段的方法,因为它们都使用相同的转换(1000)和延迟(5000)?

var c1 = 0;
setInterval(function () {
    var colors = ['#de7056', '#4ec67f']
    if (c1 > colors.length - 1) c1 = 0;
    $("#color-change1").animate({
        backgroundColor: colors[c1++]
    }, 1000);
}, 5000);

var c2 = 0;
setInterval(function () {
    var colors = ['#de7056', '#4ec67f']
    if (c2 > colors.length - 1) c2 = 0;
    $("#color-change2").animate({
        svgFill: colors[c2++]
    }, 1000);
}, 5000);

var c3 = 0;
setInterval(function () {
    var colors = ['#536260', '#fff']
    if (c3 > colors.length - 1) c3 = 0;
    $("#color-change3").animate({
        color: colors[c3++]
    }, 1000);
}, 5000);

var c4 = 0;
setInterval(function () {
    var colors = ['#536260', '#fff']
    if (c4 > colors.length - 1) c4 = 0;
    $("#color-change4").animate({
        svgFill: colors[c4++]
    }, 1000);
}, 5000);

var c5 = 0;
setInterval(function () {
    var colors = ['#536260', '#fff']
    if (c5 > colors.length - 1) c5 = 0;
    $("#color-change5").animate({
        svgStroke: colors[c5++]
    }, 1000);
}, 5000);

2 个答案:

答案 0 :(得分:0)

当然可以。怎么样:

// one iteration foreach #color-change element
for(var i = 1; i < 6; i++){
    var $target = $('#color-change' + i);
    changeColor(0, $target);
}

function changeColor(color, $target){

    setTimeout(function () {
        var colors = ['#de7056', '#4ec67f'];
        $target.animate({
            backgroundColor: colors[color]
        }, 1000);

        // recursive call to change the color to a new value
        changeColor(!color ? 1 : 0, $target); 

    }, 5000);  
}

http://jsfiddle.net/f9wrtzwv/

另一个例子,如果你想使用任意数量的颜色:http://jsfiddle.net/f9wrtzwv/1/

答案 1 :(得分:0)

您可以定义一个函数,该元素将元素设置为动画,要设置动画的属性以及要循环的值数组:

function animateContinuously($elements, attr, values) {
    var i = 0, count = values.length;
    setInterval(function() {
        i = (i + 1) % count;
        var props = {};
        props[attr] = values[i];
        $elements.animate(props, 1000);
    }, 5000);
}

然后为每个元素调用它:

animateContinuously($("#color-change1"), 'backgroundColor', ['#de7056', '#4ec67f']);
animateContinuously($("#color-change2"), 'svgFill', ['#de7056', '#4ec67f']);

jsfiddle