如何使用变量更改元素的颜色?
假设我们有四个字符串(颜色).我需要给每个类元素赋予不同的1,2,3,4,1,3 ……等等:
function pressLineColors() { var a = "#eee",b = "#123",c = "#fff",d = "#ae23e5"; $('.pressLine').each(function (i) { //go througt each of this,and give them colors,so when new elements // appear,give them next color. }); }
第一个元素sholud有颜色a,第二个b,第三个c,第四个d和第五个a,……
解决方法
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/
更新
您还可以使用此答案的注释中的建议来缩短代码:
function pressLineColors() { var colors = ["#eee",len = colors.length; $.each($('.pressLine'),element) { $(this).css('color',colors[index % len]); }); }
这是一个演示:http://jsfiddle.net/SngJK/2/
更新
您还可以使用.css(‘color’,function(){})迭代每个元素,返回您想要生成元素的颜色:
$('.pressLine').css('color',style) { return colors[index % len]; });