2012-03-13 3 views
3

Как изменить цвета элементов с помощью переменных?Как динамически менять цвет элемента?

Предположим, у нас есть четыре строки (цвета). Мне нужно, чтобы дать каждому учащемуся элементу другую, 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 имеют цвет , второй б , третий с, четвертый д, и пятый , ...

ответ

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/

Update

Вы также можете использовать предложения в комментариях к этому ответу, чтобы сократить код немного:

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/

Update

Вы также можете использовать .css('color', function(){}) перебирать каждый из элементов, возвращая цвет вы хотите, чтобы элемент:

$('.pressLine').css('color', function (index, style) { 
    return colors[index % len]; 
}); 

Вот является demo: http://jsfiddle.net/SngJK/4/

+1

@jgauffin Я откатился, потому что вы удалили мои комментарии, которые объясняют код. Также '$ .each()' создает меньше накладных расходов, чем '.each()', поэтому мне нравится его использовать. – Jasper

+1

да. double edit:/ – jgauffin

+2

просто используйте 'colors [index% colors.length]', тогда нет необходимости в 'curr',' curr ++ 'или в блоке' if' – Kyle

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]); 
}); 
} 
+0

Да, правда, отредактировано, а ответы Джаспера и Кайла лучше, потому что они позволяют размер списка и длину массива элементов –

+1

, а если есть больше элементов, чем цветов? – matthewk

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

    $('.pressLine').each(function (i, ele) { 
    $(ele).css("color", a[i % a.length]); 
    }); 
} 
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; 
    }); 
} 
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; 
} 
+0

вы увеличиваете счетчик дважды! 'counter = (++ counter gdoron

Смежные вопросы