![](/img/trans.png)
[英]How to give alternating table rows different background colors using PHP
[英]Alternating table row background colors on a dynamic table
我有一個由foreach
循環生成的表。
在循環之前,我創建$iteration = 0
。 在循環開始時,它會增加$iteration
。
然后我這樣做:
if($iteration % 2 == 0) {
$greyRow = 'css for a grey row';
}
我最多只能測試三行,但是在當前規則下,似乎第二行和第三行顯示為灰色,而不是第二行。
以下將為偶數行添加一個grey
類。
echo '<tr', ($iteration & 1 ? ' class="grey"': ''), '>';
這使用按位運算符 。 這是微優化,但遠比模運算符(盡管在這些情況下眾所周知)更優化。
另外,我鼓勵您將CSS類用於偶數和奇數行,而不是內聯樣式,或者僅切換單個類(即grey
)。
echo '<tr class="', ($iteration & 1 ? 'even': 'odd'), '">';
也許您還需要使用else
語句將其設置回奇數行上的其他顏色。 在沒有看到更多實現的情況下不太確定。
if ($iteration % 2 == 0) {
$css = 'css for a grey row';
} else {
$css = 'css for a white row';
}
我喜歡做這種事情。
<style type="text/css">
.odd td { background: #eee; }
</style>
<tr class="<?= ++$iteration % 2? 'odd' : 'even'; ?>">....</tr>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.