[英]Alternative Table Row Colors
Checked already answered questions but unsuccessful.检查已经回答的问题但不成功。
I have table populated from database.我有从数据库填充的表。
How to make alternative color for each group ?如何为每个组制作替代颜色? such as this
比如这个
This is the code这是代码
<?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 } ?>
Thank you谢谢
PS聚苯乙烯
It's a no problem to create row alternative such as this创建这样的行替代方案没问题
But I looking for GROUP by ID但我按 ID 寻找 GROUP
Use css nth child.使用 css 第 n 个孩子。
For even/odd对于偶数/奇数
Tr:nth-child(even){
Background-color: #446;
}
For Class上课
Tr.bg{
Background-color: #446;
}
For more information想要查询更多的信息
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
With PHP alternating based on variable.与 PHP 基于变量交替。 This code will change class if the first letter changes.
如果第一个字母更改,此代码将更改类。
<?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
}
If you're iterating through the rows with an index, check the value of index % 2
which say's "what's the remainder, if any, of index
divided by 2
?"如果您使用索引遍历行,请检查
index % 2
的值,该值表示“ index
除以2
的余数(如果有)是多少?”
If it equals 0
then set it's class to something like even-row
otherwise set it's class to something like odd-row
.如果它等于
0
则将它的类设置为类似even-row
东西,否则将它的类设置为类似odd-row
东西。
You can use getElementsByClassName()
to get all elements and loop through the returned array, setting the background color on every second element.您可以使用
getElementsByClassName()
获取所有元素并循环遍历返回的数组,每隔一个元素设置背景颜色。 See below:见下文:
<!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>
If you want to use CSS, use nth-child.如果要使用 CSS,请使用 nth-child。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.