问题
I'm new to writing my own jQuery and received some help with this snippet of code that works as I need it to (to animate colors, with the help of jquery-color.js plugin, and then cycle/loop through them continuously):
var c = 0;
setInterval(function () {
var colors = ['#de7056', '#4ec67f']
if (c > colors.length - 1) c = 0;
$("#neck").animate({
backgroundColor: colors[c++]
}, 1000);
}, 5000);
But now I have used this snippet multiple times to (var c1, var c2, etc.) change the color, background colour, svgFill and svgStroke (with the help of svg animate plugins) of multiple elements (#color-change1, #color-change2, etc.) and I'm wondering if there is a way to combine all of the snippets since they are all using the same transition (1000) and delay (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);
回答1:
You could define a function that takes the element to animate, the attribute to animate, and the array of values to cycle through:
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);
}
Then call it for each element:
animateContinuously($("#color-change1"), 'backgroundColor', ['#de7056', '#4ec67f']);
animateContinuously($("#color-change2"), 'svgFill', ['#de7056', '#4ec67f']);
jsfiddle
回答2:
Sure you can. How about this:
// 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/
Another example if you want to use any number of colors: http://jsfiddle.net/f9wrtzwv/1/
来源:https://stackoverflow.com/questions/26950616/how-to-possible-to-combine-these-variables-and-animate-functions