开发者

Dynamically Changing HTML

开发者 https://www.devze.com 2022-12-20 01:35 出处:网络
I am trying to create a HTML page where the \"body\" color changes depending on some data being gathered from the RAM.If the RAM fills up beyond a certain threshold then I want the color to c开发者_如

I am trying to create a HTML page where the "body" color changes depending on some data being gathered from the RAM. If the RAM fills up beyond a certain threshold then I want the color to c开发者_如何学Change.

    <body style="background-color:<%=
    if(MemoryPercentage < 33)
    {
        //set to green.
    }
    else if(MemoryPercentage < 66)
    {
        //set to yellow.
    }
    else
    {
            //set to red.
    }%>">

Thank you for your help,

Aaron


<body 
    style="background-color:<%= MemoryPercentage < 33? "green":
        (MemoryPercentage < 66? "yellow":"red") %>;">


I'd prefer using CSS classes and separating the logic out so it is more readable.

<style type="text/css">
.warn {
   background-color: #00ffff;
}
.error {
   background-color: #ff0000;
}
.ok {
   background-color: #00ff00;
}
</style>

<%
    var klass = MemoryPercentage < 33 : "ok" ? (MemoryPercentage < 66 ? "warn" : "error");
%>

<body class="<%= klass %>">


While you can definitely apply the style directly using the sytle attribute of the body tag (as suggested in this answer), general best practices revolving around HTML discourage this.

What you should do is place these styles in a stylesheet which is referenced on your page, and then have different names for the classes.

Then, in your code, apply the class that has the style you want depending on your logic to the class attribute of the body element.


Just an aside to the other answers:

<body id="Body" runat="server"> will make the tag accessible to Page_Load() & friends as an HtmlGenericControl, so you can handle the logic and set Body.CssClass without the template-y markup. Makes it a little less messy / easier to maintain.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号