function pressLineColors() {
//setup array of colors and a variable to store the current index
var colors = ["#eee", "#123", "#fff", "#ae23e5"],
curr = 0;
//loop through each of the selected elements
$.each($('.pressLine'), function (index, element) {
//change the color of this element
$(this).css('color', colors[curr]);
//increment the current index
curr++;
//if the next index is greater than then number of colors then reset to zero
if (curr == colors.length) {
curr = 0;
}
});
}
这是一个演示:http://jsfiddle.net/SngJK/
更新
您也可以使用 cmets 中的建议来缩短代码:
function pressLineColors() {
var colors = ["#eee", "#123", "#fff", "#ae23e5"],
len = colors.length;
$.each($('.pressLine'), function (index, element) {
$(this).css('color', colors[index % len]);
});
}
这是一个演示:http://jsfiddle.net/SngJK/2/
更新
您也可以使用.css('color', function (){}) 来遍历每个元素,返回您想要制作元素的颜色:
$('.pressLine').css('color', function (index, style) {
return colors[index % len];
});
这是一个演示:http://jsfiddle.net/SngJK/4/