替代 div 背景颜色
我的结构如下:
<div class="wrapper"...>
<a href="#"...>blah</a>
<div class="post"...>stuff</div>
</div>
它在动态页面中重复几次。我想用两种颜色替换 div 类“post”的背景颜色,但 CSS 的 nth-child 伪类似乎只适用于直接连续的项目。
有没有办法(CSS、Javascript、jQuery 等)可以改变 div 背景颜色?
I have a structure like the following:
<div class="wrapper"...>
<a href="#"...>blah</a>
<div class="post"...>stuff</div>
</div>
And it repeats throughout a dynamic page a few times. I would like to alternate the background colors of the div class "post" with two colors, but CSS's nth-child pseudo class only seems to work with items that are directly sequential.
Is there a way (CSS, Javascript, jQuery, etc.) that I can alternate the div background colors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
jQuery 的 :odd 和 :even 选择器非常方便:
HTML:
http://jsfiddle.net/thomas4g/uaYd9 /2/
编辑:
非 jQuery、快速 JS 方式:
jQuery's :odd and :even selectors are pretty handy:
HTML:
http://jsfiddle.net/thomas4g/uaYd9/2/
EDIT:
The non-jQuery, quick JS way:
jquery方式:
the jquery way:
通常我所做的就是在后端分配一个“奇数”或“偶数”的 css 类。例如,如果页面是在 PHP 中动态生成的,我会执行以下操作:
然后在类中定义您希望交替的 div 具有的颜色。
Typically what I do is assign a css class of "odd" or "even" on the back end. For example, if the page is dynamically generated in PHP, I'd do something like:
Then define in your class the colors you want the alternating divs to have.
可以使用 jquery
:odd
和:even
选择器轻松完成:http://jsfiddle.net/niklasvh/fULRZ/
Can be done with jquery
:odd
and:even
selectors quite easily:http://jsfiddle.net/niklasvh/fULRZ/
不适合你吗?
Doesn't work for you?
http://api.jquery.com/even-selector/
我希望这会对您有所帮助
http://api.jquery.com/even-selector/
I hope this will hep you