简体   繁体   English

我可以根据其内部的值使div更改其背景颜色吗?

[英]Can I make a div change its background color based on the value inside it?

I have a PHP index page where data from an array is being displayed inside <div> 's on top of a picture. 我有一个PHP索引页,其中来自数组的数据显示在图片顶部的<div>内部。 I want the <div> 's to change color based on the content inside it. 我希望<div>可以根据其中的内容更改颜色。

The idea is this: 这个想法是这样的:

I have Customer   -    Date    -    Due in

The array I mean has a structure like the following: 我的意思是数组具有如下结构:

Array(
   [0] => array('customer' => 'John', 'date' => '2012-05-11', 'due' => 9),
   [1] => array('customer' => 'Hess', 'date' => '2011-12-11', 'due' => 5),
   [2] => array('customer' => 'Mrac', 'date' => '2012-06-18', 'due' => 3)
)

Due in shows a number of days - I want the <div> to be red if the number inside it is 5 or lower. 由于显示的天数-如果<div>内部的数字为5或更小,我希望它为红色。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Within the php code, give the div a different class if "Due in" is less than or equal to 5. So in your PHP, when you're looping through your array: 在php代码中,如果“ Due in”小于或等于5,则给div一个不同的类。因此在您的PHP中,当您遍历数组时:

<?php 
  echo "<div";
  if($myArray[i]['due'] <= 5){ echo " class='dueSoon'"; }
  echo "> $myArray[i]['customer'] - $myArray[i]['date'] - $myArray[i]['due'] </div>";
?>

so that the following gets output when there's less than 5 days: 以便少于5天时输出以下内容:

<div class="dueSoon"> ... </div>

And then css: 然后css:

.dueSoon { background-color:red; }

In your PHP code, check for this condition, if the condition is being met, then add a css class to that div (for which the condition is being satisfied). 在您的PHP代码中,检查是否满足此条件,如果满足该条件,则向该div中添加一个css类(满足该条件的类)。

Define the CSS class in your CSS file. 在CSS文件中定义CSS类。

We will suppose that your array is named as results 我们假设您的数组被命名为results

CSS CSS

.red{
background-color: red;
}

The following is the PHP code that you have to use to print out this array. 以下是打印此数组所必须使用的PHP代码。

<?php foreach ($results as $result){?>
<div class="<?php if ($result['due'] < 5 || $result['due'] == 5) echo '.red';?>">
 Customer: <?php echo $result['customer']; ?>
 Date: <?php echo $result['date'];?>
 Due: <?php echo $result['due']; ?>
</div>
<?php } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM