问题
I'm working on a comments system, and I need to have every other child <div>
(even children of the first children) be selected with CSS.
For example, lets say I have this markup (omitting unneeded closing tags just for simplicity):
<body>
<div class="comment">
<div class="comment"/>
<p class="something else"/>
<div class="comment">
<div class="comment"/>
<div class="comment"/>
</div>
</div>
<div class="comment"/>
<div class="comment"/>
</body>
How can I select every other <div>
within the body (excluding <p>
)?
What I basically want is for it to turn out like this:
(Two stars is even, one star is odd, regular is neither)
<body>
**<div class="comment">**
*<div class="comment"/>*
<p class="something else"/>
**<div class="comment">**
*<div class="comment"/>*
**<div class="comment"/>**
</div>
</div>
*<div class="comment"/>*
**<div class="comment"/>**
</body>
I need it to walk through every other <div>
in order, applying the styles.
Is there anyway to do this?
回答1:
- Advanced demo with multiThread colored comments
- Simple demo
Ugh this took a while just to understand from OP that "even" / "odd" are actually not the CSS's even
and odd
but the index of appearance of a .comment
div, (nested or not).
CSS? Almost impossible if not even impossible. (possible only with nesting too much styles to cover all possibilities)
With jQuery simply like:
$('.comment').addClass(function(i){
return i%2 ? "odd" : "even";
});
where i
represents the Element's Array Index position (0,1,2,3...) of that .comment
element jquery collected on it's way. Now if i reminder 2
returns 0
add the "even"
class, else :
add the "odd"
class to that element.
CSS:
div.comment{
/* Common styles */
color:#fff;
margin:5px;
border:1px solid #000;
}
.even { background:blue; } /* jQ Index: 0, 2, 4, 6, 8... */
.odd { background:red; } /* jQ Index: ...1, 3, 5, 7... */
来源:https://stackoverflow.com/questions/25715302/how-can-i-use-nth-child-to-select-every-other-div-within-all-children