【问题标题】:How to alternate style (background color ) for div different divs?如何为 div 不同的 div 交替样式(背景颜色)?
【发布时间】:2012-03-03 14:24:38
【问题描述】:

如果我有这样的 HTML,如何在 id="container" 的 div 内交替(偶数和奇数)样式(使用 jquery 的背景色)交替(偶数和奇数)

<div id="container">
   <div></div> 
   <div></div>
   <div></div>
   <div></div>
...
</div>

我知道像这样的表

  $('#container>div:odd').css("background-color", "#ff0000");
  $('#container>div:even').css("background-color", "#00ff00");

但是所有 [div] 应该有不同的颜色...?没有 div 应该有相同的颜色..谁能帮帮我..

【问题讨论】:

    标签: jquery css jquery-selectors


    【解决方案1】:

    试试这个:

    var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];
    
    $('#someid .bar').each(function(i) {
       $(this).css('background-color', '#'+colors[i % colors.length]);
    });
    

    对于随机颜色,你可以使用这个:

    function randomColor() {
        return 'rgb('+
            Math.round(Math.random()*255)+', '+
            Math.round(Math.random()*255)+', '+
            Math.round(Math.random()*255)+')'
    }
    
    $('#someid .bar').each(function(i) {
       $(this).css('background-color', randomColor());
    });
    

    演示:

    http://jsbin.com/eqoyi4

    【讨论】:

    • 这适用于我在 Firefox 中。您没有尝试随附的演示吗?
    猜你喜欢
    • 2012-02-28
    • 2017-06-21
    • 2018-05-04
    • 1970-01-01
    • 2018-07-10
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多