在php循环中随机添加一个类
我正在我的网站上使用一个php循环。 我试图在这个循环中向div随机添加一个类“current”。 我知道如何使用jQuery来实现这一点,但我想使用php来实现这一点。 这是我的循环:在php循环中随机添加一个类,php,css,loops,random,Php,Css,Loops,Random,我正在我的网站上使用一个php循环。 我试图在这个循环中向div随机添加一个类“current”。 我知道如何使用jQuery来实现这一点,但我想使用php来实现这一点。 这是我的循环: <?php if (have_posts()) : ?> <div id="random_backgrounds"> <?php while (have_posts()) : the_post(); ?> <div id="background_directors" c
<?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; ?>
有人这样想吗
$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>
$test=['class1','class2','class3'];
有人这样想吗
$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>
$test=['class1','class2','class3'];
您可以尝试以下方法:
<?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;
?>
您可以尝试以下方法:
<?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;
?>
首先:ID在文档中必须是唯一的。你说的“随机添加类”是什么意思?首先:ID在文档中必须是唯一的。你说的“随机添加类”是什么意思?你可以先交换if条件来检查$isAlreadyActive
是否为false,这样就不必每次都生成随机数了!:)谢谢@CyrilBeeckman,有时候我的所有部门都没有加入“当前”课程。。。if循环是否每个div?我有一个doubt@mmdwc如果$ISALREADYAACTIVE==false并且您是最后一位,则无法计算您的帖子并进行另一次测试loop@CyrilBeeckman谢谢你的回复,你能帮我吗?我找不到how@mmdwc什么是have_posts()?返回数组?您可以交换if条件,先检查$isAlreadyActive
是否为false,这样就不必每次都生成随机数了!:)谢谢@CyrilBeeckman,有时候我的所有部门都没有加入“当前”课程。。。if循环是否每个div?我有一个doubt@mmdwc如果$ISALREADYAACTIVE==false并且您是最后一位,则无法计算您的帖子并进行另一次测试loop@CyrilBeeckman谢谢你的回复,你能帮我吗?我找不到how@mmdwc什么是have_posts()?返回数组?