如何动态改变元素的颜色?

时间:2012-03-13 19:32:37

标签: jquery html css jquery-selectors each

如何使用变量更改元素的颜色?

假设我们有四个字符串(颜色)。我需要给每个类元素赋予不同的一个,1,2,3,4,1,2,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 ,第五个< strong> a ,...

6 个答案:

答案 0 :(得分:7)

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", "#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/

答案 1 :(得分:5)

function pressLineColors() {
  var a = ["#eee","#123","#fff","#ae23e5"];

  $('.pressLine').each(function (i, ele) {
    $(ele).css("color", a[i % a.length]);
  });
}

答案 2 :(得分:3)

将这些颜色放在数组中

function pressLineColors() {

a = new Array();

a[0] = "#eee",
a[1] = "#123",
a[2] = "#fff",
a[3] = "#ae23e5";

var c = 0;
var size = a.length;

 $('.pressLine').each(function (i) {

      this.style.color = a[c];
      c++;
      if(c > size) c = 0;
  });
}

答案 3 :(得分:2)

创建一个变量来跟踪,一个单独的函数将允许您稍后添加元素并跟踪

/* colors in indexable array*/
var colors=["#eee", "#123","#fff","#ae23e5"];

var counter=0;
$('.pressLine').each(function () {
         $(this).css('color', colors[nextColorIndex()]);

});

function nextColorIndex(){
    var ctr=counter;
         counter=(++counter <colors.length) ? counter++ :0
         return ctr;
}

答案 4 :(得分:1)

答案 5 :(得分:1)

您需要将列表放入类似数组的对象,然后按索引访问;

function pressLineColors() {

var colors = [ 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. 

   $(this).css("color" , colors[i]);
 });
}