【问题标题】:Color html table based on 3 conditions基于 3 个条件的颜色 html 表
【发布时间】:2022-01-18 10:17:07
【问题描述】:

我在 CSS 中定义了 3 种颜色。在 HTML 中,我有表格,我希望单元格的背景颜色根据 3 个条件进行更改:

 if cell contains the text 'True'     - color green
 if cell contains the text 'False'    - color red
 if the cell contains the text 'None' - color yellow

我的CSS:

.color-green {
    background-color: green;
    color: black;
  }

  .color-yellow {
    background-color: orange;
    color: black;
  }
  
  .color-red {
    background-color: red;
    color: black;
}

我的html:

<td ng-class = "{'color-yellow':dict.status='True','color-red':dict.status=='false'}">{{ dict.status}}</td>

我首先尝试使用 2 种颜色,但这只是将我的单元格更改为带有红色背景的 True。 我很长时间没有接触过 html,但我记得这种方法适用于数字。 尝试谷歌但没有那么幸运:(

有什么方法可以用 3 种颜色做我想做的事吗?

【问题讨论】:

  • 这是 AngularJS 还是 Angular?请添加正确的标签。
  • 它是有角度的。我会添加
  • 你有dict.status='True' 这不是一个条件,而是赋值——你将 dict.status 设置为“真”。使用 == 并检查您是否希望它读取 'true' 或 'True'

标签: html css angular


【解决方案1】:

条件(三元)运算符可用于此目标。更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

以下代码使用类和{{ }},然后使用三元运算符。如果dict.status.includes('True') 返回true,则类等于color-green,否则如果dict.status.includes('False') 返回true,则类等于color-red,否则类变为color-yellow

class = "{{ dict.status.includes('True') ? 'color-green' : dict.status.includes('False') ? 'color-red' : 'color-yellow' }}

.color-green {
    background-color: green;
    color: black;
  }

  .color-yellow {
    background-color: yellow;
    color: black;
  }
  
  .color-red {
    background-color: red;
    color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="">
    Type your text in this box: 
    <input type="text" ng-model="dict.status">
    <table>
        <tr>
            <td class = "{{ dict.status.includes('True') ? 'color-green' : dict.status.includes('False') ? 'color-red' : 'color-yellow' }}">{{ dict.status}}</td>
        </tr>
    </table>
</div>

【讨论】:

    【解决方案2】:

    我认为您可以尝试使用指令 [ngClass] :

    <td [ngClass] = "{'color-yellow':dict.status='true','color-red':dict.status=='false'}">{{ dict.status}}</td>
    

    您可以在哪里为使用它的元素分配类。

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2017-11-20
      • 2021-03-25
      • 1970-01-01
      • 2015-08-18
      相关资源
      最近更新 更多