dpmkif3097 2018-03-21 07:26
浏览 8
已采纳

如何将“first”和“last”类添加到div行?

I am trying to add class first to the first div of a row and class last to the last div of a row. The number of divs in a row is user selectable and stored in a variable. the total number of divs is also user selectable and stored in a variable.

Here's what I have tried, but it adds the class only to the first row and not repeating for the rest.

$number_of_cols = 4;  //User Selectable
$posts_per_page = 16; //User Selectable

$mas_query = new WP_Query( $args );

if ( $mas_query->have_posts() ) :
    $count = 0;
    while ( $mas_query->have_posts() ) : $mas_query->the_post();
        $count++; ?>
        <div class="blog-masonry-grid-items masonry-col-<?php echo $number_of_cols; echo ( $count == 1 || $count == $number_of_cols + 1 ? ' masonry-col-first' : ''); echo ( $count == $number_of_cols ? ' masonry-col-last' : '');?>">
            <div class="grid-item-image-wrap"><?php if ( has_post_thumbnail() ) { the_post_thumbnail('medium_large'); } ?></div>
            <div class="grid-item-content-wrap"><?php the_title( '<h3 class="entry-title grid-entry-title">', '</h3>' );?></div>
        </div>
<?php endwhile; endif; ?>  

How do I make it repeat for all divs pragmatically?

Thanks

  • 写回答

2条回答 默认 最新

  • duanlisha2335 2018-03-21 07:33
    关注

    You can take advantage of the modulos operator, the remainder after a division:

    while ( $mas_query->have_posts() ) : $mas_query->the_post();
        $count++;
        // Boolean values
        $firstOfRow = ($count % $number_of_cols === 1);
        $lastOfRow = ($count % $number_of_cols === 0);
    

    When count is 1, 5, etc., the remainder is 1 and when count is 4, 8, etc. the remainder is 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀