[英]Alternative Table Row Colors
检查已经回答的问题但不成功。
我有从数据库填充的表。
如何为每个组制作替代颜色? 比如这个
这是代码
<?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 } ?>
谢谢
聚苯乙烯
创建这样的行替代方案没问题
但我按 ID 寻找 GROUP
使用 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
}
如果您使用索引遍历行,请检查index % 2
的值,该值表示“ index
除以2
的余数(如果有)是多少?”
如果它等于0
则将它的类设置为类似even-row
东西,否则将它的类设置为类似odd-row
东西。
您可以使用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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.