【问题标题】:Dynamic change of css class in the field字段中css类的动态变化
【发布时间】:2020-05-19 01:23:04
【问题描述】:

我想更改 (td) 字段中的颜色 [更改颜色 - 更改/转移到不同的 css 类?]

状况: 条件来自“if”查询。 if (sb == true) 那么什么都不会改变, if (sb == false) "[else]" 那么 (td class="InputsForUserColor1") 中的 css 类可能会更改为 class="InputsForUserColor1Change"。

注意事项 (td class="InputsForUserColor2") 不变

我的 html 代码(razor/C#): 变量“sb”在“if”之外,假设不同的值

 @for (int sth = 0; sth< ViewBag.sth; sth++)
{
                if (sb == true)
                {
                    varSth = "00:00";

                }
                else
                {
                   varSth = "20:00";

                }
                         @for (int sthElse = 0; sthElse< ViewBag.sthElse; sthElse++)
                          {
                                if (nr_columns == 2)
                                {
                                    <td id="td01" class="InputsForUserColor1"></td>
                                }
                                if (nr_columns == 3)
                                {
                                    <td id="td01" class="InputsForUserColor2"></td>
                                }
                          }
}

我的 CSS 代码:

.InputsForUserColor1, area {
    background-color: papayawhip;
    border: hidden;
    align-content: center;
    align-items: center;
    vertical-align: central;
}

.InputsForUserColor1Change, area {
    background-color: white;
    border: hidden;
    align-content: center;
    align-items: center;
    vertical-align: central;
}

我个人没有写它,因为我不知道如何接近它

【问题讨论】:

  • 您显示的代码仅适用于页面的初始加载(在服务器端呈现 CSHTML 页面)。如果在客户端浏览器显示页面时颜色应该改变,您必须使用javascript(例如,如果用户切换复选框,颜色应该改变,然后表单被发送回服务器)。是否只需要在服务器端更改颜色?
  • 我只需要在客户端的浏览器中更改颜色,另一方面我不需要有关它的信息,我不知道如何将“if”转换为html。

标签: c# html css asp.net razor


【解决方案1】:

如果颜色应该只设置一次,而页面在服务器上呈现:

  • 在 CSHMTL 页面的变量中设置目标类(带有@{} 的 Razor C# 代码块)。
  • 使用此变量的值(Razor @variableName 语法)。

    @* assume that 'sb' does not change its value inside the for loop *@
    @{ var userColor1 = sb == true ? "InputsForUserColor1" : "InputsForUserColor1Change"; }
    @for (int sth = 0; sth< ViewBag.sth; sth++) {
        @for (int sthElse = 0; sthElse< ViewBag.sthElse; sthElse++) {
            if (nr_columns == 2) {
                <td id="td01" class="@userColor1"></td>
            }
            else if (nr_columns == 3) {
                <td id="td01" class="InputsForUserColor2"></td>
            }
        }
    }
    

当页面传送到客户端浏览器时,这将使用正确的类集呈现 HTML。

如果由于客户端(浏览器)端的用户交互而需要更改颜色,这将不起作用。在这种情况下,您必须使用客户端脚本 (JavaScript) 来动态更改颜色。为此,请参阅jQuery addClass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2021-12-29
    • 2019-01-29
    • 1970-01-01
    • 2023-01-21
    相关资源
    最近更新 更多