如何根据值改变背景颜色

时间:2021-01-25 07:46:46

标签: html css angular

我列出了一张包含锦标赛结果的表格。我有最终的排名,以及锦标赛中每支球队的原始种子。我正在添加一个带有 +/- 的小气泡,显示最终放置与原始播种的比较情况。我想让背景在团队表现更差时变成深红色,在团队表现更好时使背景变成深绿色。

示例:

Team A finished 1st and was seeded 3rd -> light green
Team B finish 2nd and was seeded 30th -> dark green
Team C finished 10th was seeded 8th -> light red
Team D finish 30th and was seeded 1st -> dark red

我想对颜色的深/浅程度设置一个明显的限制,这样表现超过/低于一定数量的团队都会有相同的深色调。

我的网站是使用 Angular 构建的,但这是否可以仅使用一些简单的 CSS 来实现?

这是来自另一个已经实现此功能的网站的图片:

screenshot of example website

如您所见,左侧列出了最终成绩,右侧列出了他们与原始种子相比的表现。空白表示种子 == 完成

1 个答案:

答案 0 :(得分:2)

您可以为颜色创建一个数组

TS:

colors = [{ finished: "1st", color: "light green" }, { finished: "30th", color: "dark green"}]

遍历表格中的数据(或您喜欢的方式)并添加ngStyle

<table>
  <th>Team</th>
  <th>Finished</th>
  <tr *ngFor="let res of colors" [ngStyle]="{'background':getColor(res.finished)}">
    <td>res.whateveryourfieldiscalled</td>
    <td>res.whateveryourfieldiscalled</td>
  </tr>
</table>

然后用 ts getColor 方法添加:

getColor(finished) {
 return this.colors.filter(item => item.finished === finished)[0].color
}