Как динамически изменить цвет элемента? - PullRequest
3 голосов
/ 13 марта 2012

Как я могу изменить цвета элементов, используя переменные?

Допустим, у нас есть четыре строки (цвета).Мне нужно дать каждому элементу класса разный, 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. 
     });
}

Первый элемент должен иметь цвет a второй b , третий c , четвертый d и пятый a , ...

Ответы [ 6 ]

7 голосов
/ 13 марта 2012
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/

5 голосов
/ 13 марта 2012
function pressLineColors() {
  var a = ["#eee","#123","#fff","#ae23e5"];

  $('.pressLine').each(function (i, ele) {
    $(ele).css("color", a[i % a.length]);
  });
}
3 голосов
/ 13 марта 2012

имеют эти цвета в массиве

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;
  });
}
2 голосов
/ 13 марта 2012

Создание переменной для отслеживания, а отдельная функция позволит вам добавлять элементы позже и отслеживать

/* 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;
}
1 голос
/ 13 марта 2012

Вы должны поместить свой список в массивоподобный объект, а затем получить доступ по индексу;

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]);
 });
}
1 голос
/ 13 марта 2012

используйте addClass

http://api.jquery.com/addClass/

или

http://api.jquery.com/css/

...