试图在 php 中为 div 的循环提供 3 种不同的颜色,现在它只能工作两种。我如何为 div 实现替代颜色?这是我想要的。
风格
.redBackground { background-color:#F00; }
.blueBackground { background-color:#03F;}
.greenBackground { background-color:#6F3; }
php
<?php
$new= mysql_query("select * from tbl_news");
while ($row=mysql_fetch_array($new))
{
$x++;
$class = ($x%2 == 0)? 'redBackground': 'blueBackground' ;
echo "<tr class='$class'>";
$id = $row['id'];
$news = $row['news'];
?>
<div class="col-md-2 col-sm-12 col-xs-12 news_main_div">
<div class="md-trigger" data-modal="modal-11">
<div <?php echo "<tr class='$class'> ";?>>
<h1 style=" margin-bottom:5px;">
<strong ><?php echo $news ?></strong>
</h1></div></div><?php } ?>
最佳答案
像下面这样使用颜色数组
$color_array = array('whiteBackground', 'grayBackground', 'blueBackground');
$x=0;
while($row=mysql_fetch_array($new)){
$x++;
$class = $color_array[$x%3];
}
将来,如果您想要更多颜色,只需在数组中添加颜色类并更改 $color_arrar[$x%n]
,其中 n=number_of_color
如果你想要随机颜色,那么使用下面的代码
$color_arrar = array('whiteBackground ','grayBackground ','blueBackground ');
$size_of_array = sizeof($color_arrar);
while($row=mysql_fetch_array($new)){
$n = rand(0,$size_of_array-1);
$class = $color_arrar[$n%3];
}
关于php - 如何在 php 中为循环中的 div 提供 3 种不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36716519/