开发者

Table tr background color change

开发者 https://www.devze.com 2023-03-20 11:33 出处:网络
I\'m trying to m开发者_开发知识库ake in sort that odd <tr> and even <tr> have different color for easier reading.

I'm trying to m开发者_开发知识库ake in sort that odd <tr> and even <tr> have different color for easier reading.

Here's my code:

$show_res = mysql_query($show_query);
while ($show_row = mysql_fetch_assoc($show_res)){
$rc++;
if (($rc > 1)){
    $tr = '#cccccc';
} else {
    $tr = '#ffffff';
}?>
  <tr style="background-color:<?php echo $tr ;?>">

It doesn't work, am I missing something?


You want to use modulo %

Some examples:

  • 5 % 2 = remainder is 1
  • 4 % 2 = remainder is 0
  • 6 % 2 = remainder is 0
  • 9 % 2 = remainder is 1

So based on whether the remainder is 1 or 0 you change the color. And you want the <tr> element to be a part of your loop as that's constantly being changed from one color or the other, back and forth.

$show_res = mysql_query($show_query);
while ($show_row = mysql_fetch_assoc($show_res))
{
    $rc++;
    if ($rc % 2 == 1)
    {
        $tr = '#cccccc';
    } 
    else 
    {
        $tr = '#ffffff';    
?>
  <tr style="background-color:<?php echo $tr ;?>">
<?
    }
}
?>


$show_res = mysql_query($show_query);
while ($show_row = mysql_fetch_assoc($show_res)){
$rc++;
if (($rc > 1)){
    $tr = 'odd';
} else {
    $tr = 'even';
}?>
  <tr class="<?php echo $tr ;?>">

CSS

.odd td { background-color: #FFF; }
.even td { backgorund-color: #F6F6F6; }

Use CSS and set the color background to the TD not the TR element.


As this is strictly Display, I would recommend doing is using Javascript, not PHP.

Look how simple it can be: http://paragasu.wordpress.com/2009/01/05/alternate-table-row-color-the-easy-way/


Did you define $rc=0; anywhere?


The issue you're having appears to be that you're not resetting $rc++ after you've incremented it. Try setting it to 0 then reset it after you've incremented it to 1.


$show_res = mysql_query($show_query);
while ($show_row = mysql_fetch_assoc($show_res))
{
       if ( isset($k) and $k==1)
       {
             echo '<tr class="EvenTableRows">';
             $k=0;
        } else {
             echo  '<tr class="OddTableRows">'; 
             $k=1;
        }

      ..... more statement

}
0

精彩评论

暂无评论...
验证码 换一张
取 消