使用jquery或javascript为每个div设置不同的颜色

时间:2012-06-17 08:40:26

标签: javascript jquery

我有一个ul li div的主页,div是一个方框,顶部有3x3。 我网站的底部是代码生成标记,我有类似的东西。

我想给每个div“box”一个颜色,目前它们都是用css设计的。有没有办法用jquery来检查ul li div,如果div存在,那么为内联样式添加一种不同的颜色?我需要将颜色存储在脚本中。

这就是我的开始?:

$("div.box").css({"background-color": "color"});

这是我的示例缩减标记:

<ul>
<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>About Me</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>

<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>Pane 2</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>

<li data-target="aboutme" data-target-activation="click" style="margin-top:0px" class="tile high me">
          <div>
          <h2>Pane 3</h2>
        <h3></h3>
         <img width="48" height="48" alt="" class="icon" src="images/icons/x.png">
     </div>
</li>
</ul>

这是css:

       .tiles {
        height: 95%;
        margin: 0 auto;
        min-height: 950px;
        overflow: visible;
        padding: 10px;
        width: 957px;
    }

    .tile.high {
    float: left;
        height: 200px;
        margin-top: -100px;
        padding-left: 10px;
        width: 23.6%;
    }

    li.tile div {
        background-color: #00ABA9;
    }

    .tile div {
        background-repeat: no-repeat;
        height: 100%;
        margin: 10px 10px 0;
        overflow: hidden;
        width: 100%;

    }

2 个答案:

答案 0 :(得分:8)

循环显示div并在每个上使用不同的颜色:

// Declare colors you want to use
var myColors = [
    '#f00', '#abc', '#123'
];
var i = 0;
$('div.box').each(function() {
    $(this).css('background-color', myColors[i]);
    i = (i + 1) % myColors.length;
});

在线查询:http://jsfiddle.net/4NVRQ/

答案 1 :(得分:1)

var 

color = function(){
    return '#' + Math.floor(Math.random()*16777215).toString(16);
},
$els = $('div.box'),
colorify = function(els){
    els.each(function(){
        $(this).css('backgroundColor', color());
    });
};

colorify($els);