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

标签 php html css

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

enter image description here

风格

.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/

相关文章:

php - 如何在 php 中显示特定类别的帖子?

php - 现场活跃用户数

html - 让div取右边的 "free space"?

javascript - 如何从这个 javascript 代码中排除容器?

php - 如何防止 PhpStorm 在使用 PHPUnit 模拟时显示预期...警告?

php - MySQL 查询仅收到 1 个结果

javascript - 将 DIV 折叠到零高度

javascript - 单击父 div 时更改子颜色 div | CSS 伪

javascript - 如何使 R 中的粘性导航栏 Shiny ?

css - 将 div 与居中的表格左侧的 2 个图像对齐