简体   繁体   English

动态更改div的CSS属性类php

[英]Dynamically change a div's CSS attribute class php

After viewing 4 data I want to change a div's class. 查看4个数据后,我想更改div的类。 Suppose when it is 4 data the div will be after 4 data the div will be dynamically. 假设当它是4个数据时,div将在4个数据之后是动态的。

<div class="carousel-inner" role="listbox">
<?php 
    $i=0;
    $sql = mysqli_query($con,"SELECT * FROM product WHERE featured = 'featured' ORDER BY id DESC");
        while($row = mysqli_fetch_assoc($sql)){
        if($i == 4){ echo '<div class="item active">';}
        elseif($i != 4){ echo '<div class="item">'; }
?>
     <div class="single-wid-product sel-pd">
        <img src="admin/upload/<?php echo $row['file']; ?>" alt="" class="product-thumb">
     </div>

    </div>
    <?php $i++; } ?>

</div>

在此处输入图片说明

In that picture it is a carousel. 在那张照片中是旋转木马。 It has 4 items active. 它有4个活动项目。 And the div is 而div是

<div class="item active">
 <p>Item 1</p>
 <p>Item 2</p>
 <p>Item 3</p>
 <p>Item 4</p>
</div>

When it's doing autoplay (for the rest products) the div is 在进行自动播放时(对于其他产品),div为

<div class="item">
 <p>Item 5</p>
 <p>Item 6</p>
 <p>Item 7</p>
 <p>Item 8</p>
</div>

And for others the div is 对于其他人,div是

   <div class="item">
     <p>Item 5</p>
     <p>Item 6</p>
     <p>Item 7</p>
     <p>Item 8</p>
    </div>

So I want to make to merge all those divs. 因此,我想合并所有这些div。 For the first 4 items the div class will be "item active" and for the rest items the class will be "item". 对于前四个项目,div类将为“ item active”,而对于其余项目,该类将为“ item”。 It will be changed dynamically. 它将动态更改。

You can use a PHP ternary operator right on your HTML for this. 您可以为此直接在HTML上使用PHP三元运算符。 You can do that in this manner: 您可以通过以下方式进行操作:

while ($row = mysqli_fetch_assoc($sql)) {
    ?>
        <div class="item <?= ($i == 4) ? "active" : "" ?>">
            ...
        </div>
    <?php 

    $i++;
}

Note: <?= '' ?> is the same as <?php echo '' ?> 注意: <?= '' ?><?php echo '' ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM