如果函数返回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>

这将返回电影的元评分,由wordpress中的插件定义,作者可以在编辑帖子时键入评分。

我现在想根据电影的得分,用不同的背景色来设计结果的风格:

.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')返回的值高于6)。如果分数在4到6之间,我想使用.metacontentY。如果分数低于4,我想使用.metacontentR。

我该如何解决这个问题?

首先做一个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>

更新函数the_field以返回array(score => 6, class =>metacontentR)或类似内容,然后在html中可以将该字符串用作类

<div class="<?php the_field('metascore')['class'] ?>"><div><span> <?php the_field('metascore')['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> 

您也可以尝试使用切换案例

$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>