0

我一直在尝试寻找替代 div 的背景颜色。我总共有 11 种颜色,需要在它们之间循环,而不会连续出现两次相同的颜色。我已经查看了 css 中的第 n 个孩子,但无济于事,最终在几行中出现了所有相同的颜色。现在我正在尝试通过 javascript 中的 for 循环来实现。有谁知道更简单的方法?我有这个,它经历了很多次迭代。我只是停留在这一点上。

function ColorChange(){
    var divcount = $('.time').length;
    var timediv = document.getElementsByClassName('time'); 
    var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333"); 
    for(var i = 0; i<timediv.length; i++){
        for(var l = 0; l<mycolors.length;l++){
            timediv[i].style.background = mycolors[l]; 
        }
    }
}
4

4 回答 4

3

您似乎有效地将背景颜色设置为列表中的最后一种颜色。为什么不试试这个:

for( var i=0; i<timediv.length; i++) {
    timediv[i].style.backgroundColor = mycolors[i % mycolors.length];
}

这将循环通过定义的颜色,并且由于%操作员,如果它超过结尾,它将循环到列表的开头。

于 2013-09-23T18:13:57.740 回答
0

您可以创建一个实用程序类来帮助骑自行车。

这是此类的一个示例。您可以将其传递给一个数组并通过调用next().

http://jsfiddle.net/3Gw9C/

function Cycler (collection) {
    this.collection = collection;
    this.index = 0;

    this.next = function () {
        if (this.index >= this.collection.length) {
            this.index = 0;
        }
        return this.collection[this.index++];
    }
}

var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333");

var cycler = new Cycler(mycolors);

for (var i = 0; i < timediv.length; i++) {
    timediv[i].style.backgroundColor = cycler.next();
}
于 2013-09-23T18:16:13.477 回答
0

您似乎混合使用了 jquery 和 javascript。所以我去了jquery路线

http://jsfiddle.net/bhlaird/NyKFf/

function ColorChange(){

    var count = 0;
    var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333"); 
    $('.time').each(function() {
        $(this).css('background-color', mycolors[count++]);
        if (count > mycolors.length) count = 0;
    });

}
于 2013-09-23T18:22:08.400 回答
0

另一种选择是纯 css 路由:http: //jsfiddle.net/bhlaird/9Hbmr/

#colors .time:nth-child(11n) {
    background-color:#0066cc;
}
#colors .time:nth-child(11n+1) {
    background-color:#996699;
}
#colors .time:nth-child(11n+2) {
    background-color:#990033;
}
#colors .time:nth-child(11n+3) {
    background-color:#ff9933;
}

ETC

于 2013-09-23T18:28:08.750 回答