我使用的表与交替行颜色与此。

t.d. d0 t.d. background-color: # CC9999; 颜色:黑; 的 tr.d1 td background-color: # 9999CC; 颜色:黑; 的 < table > < tr =“d0级> 一号< td > < / td > 一号< td > < / td > < / tr > < tr课=“d1”> 二< td > < / td > 二< td > < / td > < / tr > - < table >

在这里,我将class用于tr,但我只想用于table。当我使用类表比这适用于tr替代。

我可以写我的HTML像这样使用CSS吗?

<table class="alternate_color">
    <tr><td>One</td><td>one</td></tr>
    <tr><td>Two</td><td>two</td></tr>
    </table>

我如何能使行有“斑马条纹”使用CSS?


当前回答

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

其他回答

你有:n -child()伪类:

table tr:nth-child(odd) td{
    ...
}
table tr:nth-child(even) td{
    ...
}

在:n -child()的早期,它的浏览器支持有点差。这就是为什么设置class="odd"成为一种常见的技术。在2013年底,我很高兴地说IE6和IE7终于死了(或者病得不再关心了),但IE8还在——谢天谢地,它是唯一的例外。

<script type="text/javascript">
$(function(){
  $("table.alternate_color tr:even").addClass("d0");
   $("table.alternate_color tr:odd").addClass("d1");
});
</script>

你可以使用n -child(奇数/偶数)选择器,但不是所有的浏览器(如6-8,ff v3.0)都支持这些规则,因此,为什么大多数解决方案都退回到某种形式的javascript/jquery解决方案,为这些不兼容的浏览器添加类行,以获得老虎条纹效果。

只需将以下内容添加到html代码中(在<head>内),就完成了。

HTML:

<style>
      tr:nth-of-type(odd) {
      background-color:#ccc;
    }
</style>

比jQuery示例更简单、更快。

我能用这样的方式编写HTML吗 css呢?

是的,你可以,但你将不得不使用:n -child()伪选择器(虽然有有限的支持):

table.alternate_color tr:nth-child(odd) td{
    /* styles here */
}
table.alternate_color tr:nth-child(even) td{
   /* styles here */
}