【问题标题】:randomly add a class inside a php loop在 php 循环中随机添加一个类
【发布时间】:2017-05-15 14:32:55
【问题描述】:

我在我的网站上使用 php 循环。 我正在尝试将一个类“当前”随机添加到此循环内的 div 中。 我知道如何使用 jQuery 来做到这一点,但我想使用 php 来实现这一点。 这是我的循环:

<?php if (have_posts()) : ?>
<div id="random_backgrounds">
<?php while (have_posts()) : the_post(); ?>
<div id="background_directors" class="" background_ID="<?php the_ID();?>" style="background: url(<?php the_post_thumbnail_url( 'large' ); ?>) no-repeat center center fixed" ></div>
<?php endwhile; ?>
</div>
<?php endif; ?>

我想将“当前”类随机添加到“background_directors”div。

谁能帮我解决这个问题?

【问题讨论】:

  • 首先:ID 在文档中必须是唯一的。
  • 你是什么意思“随机添加一个类”?

标签: php css loops random


【解决方案1】:

你可以试试这样的:

<?php 
    if (have_posts()) : 
        $numberPost = count(have_posts());
        $isAlreadyActive = false;
        $i = 1;
        echo '<div id="random_backgrounds">';
        while (have_posts()) : 
            the_post();
            $class = "";
            if(!$isAlreadyActive && rand(0, 1) == 1 || !$isAlreadyActive && $i == $numberPost): 
                $class = "current"; 
                $isAlreadyActive = true;
            endif;
            echo '<div id="background_directors" class="' . $class . '" background_ID="' . the_ID() . '" style="background: url(' . the_post_thumbnail_url( "large" ) . ') no-repeat center center fixed" ></div>';
            $i++;
        endwhile;
        echo '</div>';
    endif; 
?>

【讨论】:

  • 您可以先交换 if 条件以检查 $isAlreadyActive 是否为假,这样就不必每次都生成随机数! :)
  • 感谢@CyrilBeeckman,有时我的 div 都没有添加“当前”类... if 循环每个 div 吗?我有疑问
  • @mmdwc 如果 $isAlreadyActive == false 并且您在最后一个循环中,您无法计算您的帖子并进行另一次测试
  • @CyrilBeeckman 谢谢你的回复,你能帮我做吗?我找不到方法
  • @mmdwc 什么是 have_posts() ?返回一个数组?
【解决方案2】:

这样想吗?

$test = ['class1', 'class2', 'class3'];


<div id="background_directors" class="<?=$test[rand(0,2)]?>" background_ID="<?php the_ID();?>" style="background: url(<?php the_post_thumbnail_url( 'large' ); ?>) no-repeat center center fixed" ></div>

【讨论】:

    猜你喜欢
    • 2012-04-25
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2014-01-23
    相关资源
    最近更新 更多