简体   繁体   English

使用javascript更改html中奇数/偶数DIV的颜色

[英]change color of odd/even DIVs in html using javascript

For example we 5 DIVs: 例如我们5 DIV:

<div id="container" >
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
</div>

How can I change the background color of even DIVs? 如何更改偶数DIV的背景颜色?

CSS3 - not working in older browsers such as IE8 CSS3 - 不适用于IE8等旧版浏览器

#container2 > div:nth-child(even){
  background: yellow;
}

jQuery which does work in IE8 too jQuery也可以在IE8中运行

$("#container > div:nth-child(even)").addClass("even");

I also found this discussion: IE8 and jQuery selectors 我也发现了这个讨论: IE8和jQuery选择器

Here is a DEMO of CSS3 and jQuery both 这是CSS3和jQuery演示

 $("#container1 > div:nth-child(even)").addClass("even"); 
 .even { background-color: yellow } #container2>div:nth-child(even) { background: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> jQuery: <div id="container1"> <div class="child">1</div> <div class="child">2</div> <div class="child">3</div> <div class="child">4</div> <div class="child">5</div> </div> <hr/> CSS3: <div id="container2"> <div class="child">1</div> <div class="child">2</div> <div class="child">3</div> <div class="child">4</div> <div class="child">5</div> </div> 

If you wanted a javascript option for some reason (maybe you're looking to do more than just a class?) you could use the each() function in jquery. 如果你出于某种原因想要一个javascript选项(也许你想要做的不仅仅是一个类?)你可以在jquery中使用each()函数。 Here is a functioning example to boot! 是一个启动的功能示例!

CSS CSS

.redBox{
    background-color: #ff0000;
}​

Javascript 使用Javascript

var i = 0;
$(".child").each(function(i){
    if(i%2===0){
        $(this).addClass("redBox");
    }
    i++;
});

try nth-child demo 试试nth-child demo

div:nth-child(even){
background: yellow;
}

div{
 background: red;
}

用CSS做吧?

#container child:nth-child(even) {background: #CCC}

You can also use CSS3 nth-child selector. 您还可以使用CSS3 nth-child选择器。 You can find samples on Here 你可以在这里找到样品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM