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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集