如何在php中为循环中的div提供3种不同的颜色

ub_*_*303 3 html css php

试图为 php 中的 div 循环提供 3 种不同的颜色,现在它只能工作两种。我如何为 div 实现替代颜色。?这里有我想要的。

在此处输入图片说明

风格

.redBackground { background-color:#F00; }
.blueBackground { background-color:#03F;}
.greenBackground { background-color:#6F3; }
Run Code Online (Sandbox Code Playgroud)

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 } ?>
Run Code Online (Sandbox Code Playgroud)

小智 5

使用如下所示的颜色数组

$color_array = array('whiteBackground', 'grayBackground', 'blueBackground');

$x=0;
while($row=mysql_fetch_array($new)){
    $x++;
    $class = $color_array[$x%3];
}
Run Code Online (Sandbox Code Playgroud)

将来,如果您想要更多颜色,只需在数组中添加 color-class 并更改 in $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];
}
Run Code Online (Sandbox Code Playgroud)