备用表格行颜色

时间:2018-11-15 18:49:24

标签: php html

检查已回答的问题,但未成功。

我有从数据库填充的表。

如何为每组设置其他颜色?例如

enter image description here

这是代码

<?php
while ( $rq  = sqlsrv_fetch_array( $result_N, SQLSRV_FETCH_ASSOC)) {
?>

<div class="center2">
  <div class="datagrid">
    <table>
        <tr><td> <?php echo $rq[category_id]; ?></td></tr>
    </table>
    </div>
</div>
<?php } ?>

谢谢

P.S。

创建这样的行替代品

没问题

enter image description here

但是我要按ID查找GROUP

3 个答案:

答案 0 :(得分:2)

使用css第n个孩子。

对于偶/奇

Tr:nth-child(even){
 Background-color: #446;
}

对于班级

Tr.bg{
 Background-color: #446;
}

更多信息

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

使用PHP基于变量交替进行。如果首字母更改,则此代码将更改类。

<?php

 $first_letter  '';
 //Change class to true to invert background color
 $class = false;


//Warning isn't Category id supposed to be a string is so add quotes

 while ( $rq = sqlsrv_fetch_array( $result_N, SQLSRV_FETCH_ASSOC)) { 
//Using shorthand echo <?=
//

     // CSS Class Name
    $val = (string) trim( strtolower( $rq[category_id] ) ); //Make sure its of string type

    //This will set the class to either true or false
    //If class is true, the column will have a classname of bg
    if( !empty( trim($rq[category_id]) ) && strlen( $val ) > 0 && $first_letter !== $val[0];   ){
        $class = !$class; //Invert class
        $first_letter = $val[0];
    }

   ?> <div class="center2"> 
    <div class="datagrid"> 
       <table> 
          <tr class='<?= $class ? 'bg' : null  ?>' ><td> <?php echo $rq[category_id]; ?></td></tr> 
       </table> 
    </div> 
   </div><?php

} 

答案 1 :(得分:-1)

如果要遍历带有索引的行,请检查index % 2的值,该值表示“ index的余数除以2是多少吗?” < / p>

如果它等于0,则将其类设置为even-row,否则将其类设置为odd-row

答案 2 :(得分:-1)

您可以使用getElementsByClassName()获取所有元素并遍历返回的数组,在每隔一个元素上设置背景色。见下文:

<!DOCTYPE HTML>
<html>
  <body>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
    <p class="row">A Row</p>
  </body>
  <script>
    const rows = document.getElementsByClassName('row');
    for (i=0;i<rows.length;i+=2)
      rows[i].style.backgroundColor = "blue";
  </script>
</html>

如果要使用CSS,请使用nth-child。

相关问题