简体   繁体   English

交替的行颜色

[英]alternating row colors

I am looking for a solution to use the alternating colors row design in my table which is from a csv. 我正在寻找一个解决方案,使用我的表中的交替颜色行设计,来自csv。

my code: 我的代码:

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr class='odds'>";
        foreach ($line as $cell) {
                      echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table>";
?>

so how can i have the tr class to alternate from odds and even? 那么我怎么能让tr类从赔率甚至? thanks 谢谢

have a variable 有一个变量

int count =0; int count = 0;

increment count on every iteration and take modolous by 每次迭代时递增计数并采用模态

count % 2 数%2

if(count % 2 == 0)
color = red //(make color of row = red)

else
color = yellow //(make color of row = yello)

count=count+1;

thats just an idea, u can accomodate this in ur code 这只是一个想法,你可以在你的代码中容纳这个

<?php
echo "<table style='text-align: left; width: 99%;' border='1'>\n\n
<thead>
<tr>
<th>data</th>

</tr>
</thead>";
$f = fopen("local/datafiles.csv", "r");
$i = 0;
while (($line = fgetcsv($f)) !== false) {
    echo "<tr style='background-color: ".(($i%2)?'green':'blue').";'>";
    foreach ($line as $cell) {
        echo "<td style='font-weight: bold;'>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>\n";
    $i++;
}
fclose($f);
echo "\n</table>";
?>

Or you could assign a class just the same way and style it using css. 或者您可以使用css以相同的方式分配类并对其进行样式设置。 This is much better practice. 这是更好的做法。

You could use the css pseudo-selector :nth-of-type(odd|even) 你可以使用css伪选择器:nth-​​of-type(odd | even)

http://reference.sitepoint.com/css/pseudoclass-nthoftype http://reference.sitepoint.com/css/pseudoclass-nthoftype

If the ID of the table is styledTable, your stylesheet would look like: 如果表的ID是styledTable,则样式表将如下所示:

#styledTable {
 text-align: left;
 width: 99%;
 border: 1px solid black;
}

#styledTable tr:nth-of-type(even) {
 background-color: red;
}

#styledTable tr:nth-of-type(odd) {
 background-color: blue;
}

I will give you a better but much simpler solution, through CSS. 我将通过CSS为您提供更好但更简单的解决方案。 First of all uniquely identify your table, i will show you a more general option. 首先,唯一标识您的表格,我将向您展示更一般的选项。

table tr { backgroun: #ddd; }
table tr:nth-child(2n) { background: #ccc; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM