简体   繁体   English

动态表上的交替表行背景色

[英]Alternating table row background colors on a dynamic table

I have a table generated by a foreach loop. 我有一个由foreach循环生成的表。

Before the loop, I create $iteration = 0 . 在循环之前,我创建$iteration = 0 At the beginning of the loop it increments $iteration . 在循环开始时,它会增加$iteration

Then I do this: 然后我这样做:

if($iteration % 2 == 0) { 
  $greyRow = 'css for a grey row'; 
}

I've only three rows, at max, to test this with, but it seems that it greys the 2nd and 3rd row under the current rule, rather than only the second. 我最多只能测试三行,但是在当前规则下,似乎第二行和第三行显示为灰色,而不是第二行。

This following will add a grey class for even rows. 以下将为偶数行添加一个grey类。

echo '<tr', ($iteration & 1 ? ' class="grey"': ''), '>';

Note 注意

This uses a bitwise operator . 这使用按位运算符 It's a micro-optimization but far more optimal than the modulus operator (although notoriously used in these cases). 这是微优化,但远比模运算符(尽管在这些情况下众所周知)更优化。

Also, I would encourage you to utilize CSS classes for even and odd rows versus inline styles or just toggling a single class (ie grey ). 另外,我鼓励您将CSS类用于偶数和奇数行,而不是内联样式,或者仅切换单个类(即grey )。

echo '<tr class="', ($iteration & 1 ? 'even': 'odd'), '">';

Perhaps you also need to have an else statement to set back to the other color on the odd rows. 也许您还需要使用else语句将其设置回奇数行上的其他颜色。 Not quite sure without seeing more of your implementation. 在没有看到更多实现的情况下不太确定。

if ($iteration % 2 == 0) {
    $css = 'css for a grey row';
} else {
    $css = 'css for a white row';
}

I like to do this kind of thing.. 我喜欢做这种事情。

<style type="text/css">
.odd td { background: #eee; }
</style>
<tr class="<?= ++$iteration % 2? 'odd' : 'even'; ?>">....</tr>

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

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