red*_*gem 14 javascript css jquery dom pseudo-class
我有如下结构:
<div class="wrapper"...>
   <a href="#"...>blah</a>
   <div class="post"...>stuff</div>
</div>
它会在动态页面中重复几次.我想用两种颜色替换div类"post"的背景颜色,但CSS的nth-child伪类似乎只适用于直接顺序的项目.
有没有办法(CSS,Javascript,jQuery等),我可以交替div背景颜色?
Tho*_*lds 27
jQuery的:奇数和:偶数选择器非常方便:
$(".post:even").css("background-color","blue"); 
$(".post:odd").css("background-color","red"); 
HTML:
<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
<div class="wrapper">
   <a href="#">blah</a>
   <div class="post">stuff</div>
</div>
...
http://jsfiddle.net/thomas4g/uaYd9/2/
编辑:
非jQuery,快速JS方式:
var posts = document.getElementsByClassName("post");
for(var i=0;i<posts.length;i++) {
  posts[i].classList.add(i % 2 === 0 ? "even" : "odd");
  //or
  posts[i].style["background-color"] = i % 2 === 0 ? "blue" : "red";
}
jquery方式:
$('.post:even').css('background-color','green');
$('.post:odd').css('background-color','red');
| 归档时间: | 
 | 
| 查看次数: | 10275 次 | 
| 最近记录: |