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

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?


当前回答

在PHP中有一个相当简单的方法来做到这一点,如果我理解您的查询,我假设您在PHP中编码,您正在使用CSS和javascript来增强输出。

来自数据库的动态输出将携带一个for循环来遍历结果,然后将结果加载到表中。只需要像这样添加一个函数调用:

echo "<tr style=".getbgc($i).">";  //this calls the function based on the iteration of the for loop.

然后将函数添加到页面或库文件中:

function getbgc($trcount)
{

$blue="\"background-color: #EEFAF6;\"";
$green="\"background-color: #D4F7EB;\"";
$odd=$trcount%2;
    if($odd==1){return $blue;}
    else{return $green;}    
}

现在,这将在每个新生成的表行中动态地在颜色之间交替。

这比在所有浏览器上都不能工作的CSS要容易得多。

希望这能有所帮助。

其他回答

以上大部分代码都不能在IE版本下使用。适用于IE+其他浏览器的解决方案是这样的。

   <style type="text/css">
      tr:nth-child(2n) {
             background-color: #FFEBCD;
        }
</style>

你可以使用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 */
}

你有:n -child()伪类:

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

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