如果函数 returns 数字介于 0 和 6 之间,则更改背景颜色

Change color of background if function returns number between 0 and 6

我在网站上显示了一个 PHP 函数:

<div class="metacontent"><div><span> <?php the_field('metascore'); ?> </span></div> </div>

这 returns 电影的元乐谱,由 wordpress 中的插件定义,作者可以在编辑 post 时键入乐谱。

我现在想根据电影的得分为结果设置不同背景颜色的样式:

.metacontentG {
    position: relative;
    width: 52px;
    height: 52px;
    background-color: #6c3;
}

.metacontentY {
    position: relative;
    width: 52px;
    height: 52px;
    background-color: #fc3;
}

.metacontentR {
    position: relative;
    width: 52px;
    height: 52px;
    background-color: #f00;
}

换句话说,如果分数高于 6,我想使用 .metacontentG(函数 the_field('metascore') returns 高于 6 的值)。如果分数在 4 到 6 之间,我想使用 .metacontentY。如果分数低于 4,我想使用 .metacontentR。

我该如何解决这个问题?

将您的函数 the_field 更新为 return array(score => 6, class =>metacontentR) 或类似的东西,然后在您的 html 中您可以将字符串用作 class

<div class="<?php the_field('metascore')['class'] ?>"><div><span> <?php the_field('metascore')['score']; ?> </span></div> </div>

先做一个if语句判断自己属于哪一类:

$score = get_field('metascore'); 

if($score < 4) {    
  $class = "R";
} elseif($score < 6) {
  $class = "Y";
} else {
  $class = "G";
}

然后这样回显:

<div class="metacontent<?php echo $class; ?>"><div><span> <?php echo $score; ?> </span></div> </div>

您可以用作:-

<?php
$response = the_field('metascore')
?>
<div class="<?php if($response==1) { echo "metacontentG"; } if($response==2) { echo "metacontentC"; } ?>"><div><span> <?php the_field('metascore'); ?> </span></div> 

你也可以试试 switch case

$mscore = get_field('metascore'); 
$className = "G";
if($mscore !="")
{
    if($mscore > 4 && $mscore < 6) {    
        $className = "Y";
    } elseif($mscore > 6) {
        $className = "G";
    } elseif($mscore < 4) {
        $className= "R";
    }
}

<div class="<?php print $className;?>" ><div><span> <?php the_field('metascore'); ?> </span></div> </div>