Blazor - 根据条件更改文本颜色

问题描述 投票:0回答:2

我有这五个评分:

    if (model.CIIattainedrequired2021 > model.d4)
    {
        model.CIIrating2021 = "E";
    }
    if (model.CIIattainedrequired2021 < model.d4)
    {
        model.CIIrating2021 = "D";
    }
    if (model.CIIattainedrequired2021 < model.d3)
    {
        model.CIIrating2021 = "C";
    }
    if (model.CIIattainedrequired2021 < model.d2)
    {
        model.CIIrating2021 = "B";
    }
    if (model.CIIattainedrequired2021 < model.d1)
    {
        model.CIIrating2021 = "A";
    }

我将它们显示在表格中:

    <td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2019</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2020</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2021</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2022</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2023</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2024</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2025</p>
</td><td class="text-center px-2 py-1 mx-0 text-xs">
    <p>@model.CIIrating2026</p>

根据答案,我想以不同的颜色显示文本,如下所示:

A-绿色 B-浅绿色 C-黄色 D-橙 E-红

c# html css blazor
2个回答
4
投票

对于文本,添加以下内容:

<p style="color:@TextColor(model.CIIrating2020);">@model.CIIrating2020</p>

然后在您的代码中添加类似的内容以根据文本返回正确的颜色:

private string TextColor(string text) {
switch(text) 
{
  case "A":
    return "#00FF00"
    break;
  case "B":
    return "#90EE90"
    break;
  //etc....
}
}

0
投票
  1. 您需要的第一件事是使用变量添加一个类 在你的 td 元素中。
<td class="text-center px-2 py-1 mx-0 text-xs Add a class
        variable here like :@Color-code" >
  1. 然后在页面/组件的代码部分中,您需要用作上面的类的变量以及根据您的逻辑切换类的方法:
@code{
    private string Color-code{get;set;}

     -//method that identifies the color

     private void setColorClassMethod(){

         if(condition){
             //Assuming you want to assign blue class in the case
             Color-Code="blueClass";
        }
    }
}
  1. 最后在 site.css 文件中为上面在变量中使用的类添加颜色,例如:
.blueClass{
 //if you want to change background color
 background-color:blue;
 
 //if you want to change text color
 color:blue;
}

您也可以通过 in line css 达到相同的结果。但我建议使用类,因为您可能需要稍后向 td 添加进一步的样式。

© www.soinside.com 2019 - 2024. All rights reserved.