向循环中的第一个div添加不同的类 [英] Adding different class to first div in loop

查看:216
本文介绍了向循环中的第一个div添加不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<div class="item">
  <?php the_post_thumbnail('full');?>
  <div class="container">
    <div class="carousel-caption">
      <h1>
        <?php the_title(); ?>
      </h1>
      <p>
        <?php the_excerpt(); ?>
      </p>
    </div>
  </div>
</div>
<?php endwhile; ?>

我需要将类active添加到第一个div

And I need to add the class "active" to the first div (next to "item")

推荐答案

使用布尔变量进行测试,首次传递后将其设置为true, p>

Use a boolean variable to test, set it to true after first pass so that further loops will not mark it active

<?php $firstMarked = false; ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="item <?php echo !$firstMarked ? "active":"";?>">
  <?php the_post_thumbnail('full');?>
  <div class="container">
    <div class="carousel-caption">
      <h1>
        <?php the_title(); ?>
      </h1>
      <p>
        <?php the_excerpt(); ?>
      </p>
    </div>
  </div>
</div>
<?php $firstMarked = true;?>
<?php endwhile; ?>

这篇关于向循环中的第一个div添加不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆