【问题标题】:Is there a way to use a field's value in the Model to set a style attribute dynamically?有没有办法在模型中使用字段的值来动态设置样式属性?
【发布时间】:2022-01-07 14:20:06
【问题描述】:

我创建了一个 CSHTML 电子邮件模板文件,用于在特定事件即将结束时发送警报(即在结束前 10 分钟发送警报,然后在结束前 5 分钟发送警报,等等)。我想通过颜色突出显示事件的类型(因为可以有多个)以区分消息。我目前拥有的是这样的:

<strong style="color: {event color}">@alert.event</strong> is scheduled to end: <strong>@endEasternTime

我希望能够根据 @alert.event 中的值设置 {事件颜色},但我不确定是否可以。我试图在文件中创建一个脚本,但我不确定如何将其返回值放入样式标签中:

<script>
    // Get the root element
    var r = document.querySelector(':root');

    // Create a function for getting a variable value
    function getEventColor(event) {
        // Get the styles (properties and values) for the root
        var rs = getComputedStyle(r);

        // Get the color associated with the event (default is the border color)
        return (event === "event1"
            ? rs.getPropertyValue('--evt1Color')
            : (event === "event2"
                ? rs.getPropertyValue('--evt2Color')
                : (event === "event3"
                    ? rs.getPropertyValue('--evt3Color')
                    : rs.getPropertyValue('--bdrColor')
                    )
                )
            );
    }
</script>

请注意,我在文件中创建了 HTML 变量以将颜色与文件中的其他样式(例如 border-color)相匹配——出于空间考虑和清晰度,我没有将在此处显示。

有没有办法做到这一点?如果不使用上面的内联 CSS,我可以更新 class 或 id 使用类似于上面的 script 方法,如果是这样,最好的方法是什么。感谢您的帮助。

【问题讨论】:

  • 否则使用.. @if (@alert.event == value1) { &lt;strong class= "color1"&gt; else if (@alert.event == value2){ &lt;strong class= "color2"&gt; }

标签: javascript c# asp.net razor


【解决方案1】:

你可以使用 if.. else..

@if (@alert.event == value1) 
{     
     <strong class="color1">
}
else if (@alert.event == value2)
{     
    <strong class="color2"> 
}
else {
    <strong class="colorn">
}

或者更简单的方法是根据您的事件命名类并使用 CSS 添加颜色。

<strong class="event @alert.event">

标签有 2 个类(事件和生成的值)

假设@alert.event = "test",然后将CSS添加到类中,如下所示。

.event.test {
    color: <color code>
}

【讨论】:

  • 感谢 Akash,我尝试了您的“更简单的方法”,效果非常棒!谢谢...这困扰了我一段时间。
  • @MarkLinebarger 没问题马克!
  • 只是出于好奇,如果我有十个事件,其中五个应该具有相同的颜色,我将如何对这五个进行分组?还是我必须单独设置每个课程(如您在上面的“.event.test”示例中所示)?
  • 您可以根据需要为一行中的所有事件设置颜色。 .event.test1, .event.test2, .event.test3 { color: &lt;color code&gt; }
  • 知道了...再次感谢。我错过了逗号(,)分隔符。感谢您的帮助!
猜你喜欢
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
相关资源
最近更新 更多