How do you change the style of a div programmatically

后端 未结 8 2545
攒了一身酷
攒了一身酷 2021-02-20 06:56

How do I change the style (color) of a div such as the following?

\"
相关标签:
8条回答
  • 2021-02-20 06:59

    If you want to alter the color of the div with client side code (javascript) running in the browser, you do something like the following:

    <script>
     var fooElement = document.getElementById("foo");
     fooElement.style.color = "red"; //to change the font color
    </script>
    
    0 讨论(0)
  • 2021-02-20 07:09

    It looks like you are writing ASP, or maybe JSP. I'm not too familiar with either language, but the principles are the same no matter what language you are working in.

    If you are working with a limited number of colours, then the usual option is to create a number of classes and write rule-sets for them in your stylesheet:

    
    .important { background: red; }
    .todo { background: blue; }
    

    And so on.

    Then have your server side script generate the HTML to make the CSS match:

    
    <div class="important">
    

    You should, of course, ensure that the information is available through means other than colour as well.

    If the colours are determined at run time, then you can generate style attributes:

    
    <div style="background-color: red;">
    
    0 讨论(0)
  • 2021-02-20 07:15

    Try this: in the .aspx file put thees lines

    <div id="myDiv" runat="server">
        Some text
    </div>
    

    then you can use for example

    myDiv.Style["color"] = "red";
    
    0 讨论(0)
  • 2021-02-20 07:15

    You should set your colors in CSS, and then change the CSS class programatically. For example:

    (CSS)

    div.Error {
      color:red;
    }
    

    (ASP.NET/VB)

    <div class='<%=Iif(HasError, "Error", "")%>'> .... </div>
    
    0 讨论(0)
  • 2021-02-20 07:16

    If you wanted to change the class instead of the style directly: ie.. create another class with the styling you want...

    myDiv.Attributes["class"] = "otherClassName"
    
    0 讨论(0)
  • 2021-02-20 07:16

    That code fragment doesn't say much - if the code is server-side why don't you change e.g. the class of the HTML element there?

    0 讨论(0)
提交回复
热议问题