0

divの背景色を交互に変える方法を見つけようとしています。合計 11 色あり、同じ色が 2 回続けて表示されないように循環する必要があります。私は css で nth-child を調べましたが、何行も同じ色になってしまいました。今、私は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;
}

于 2013-09-23T18:28:08.750 に答える