[英]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.