How do you change the style of a div programmatica

2020-07-05 06:43发布

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

"<div id=foo class="ed" style="display: <%= ((foo.isTrue) ? string.Empty : "none") %>">
                        <%= ((foo.isTrue) ? foo.Name: "false foo") %>"`

8条回答
Lonely孤独者°
2楼-- · 2020-07-05 07:20

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>
查看更多
虎瘦雄心在
3楼-- · 2020-07-05 07:21

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?

查看更多
姐就是有狂的资本
4楼-- · 2020-07-05 07:24

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";
查看更多
爷的心禁止访问
5楼-- · 2020-07-05 07:27

IMO this is the better way to do it. I found some of this in other posts but this one comes up first in google search.

This part works for standard JavaScript. I am pretty sure you can use it to remove all styles as well as add/overwite.

var div = document.createElement('div');
div.style.cssText = "border-radius: 6px 6px 6px 6px; height: 250px; width: 600px";

OR

var div = document.getElementById('foo');
div.style.cssText = "background-color: red;";

This works for jQuery only

$("#" + TDDeviceTicketID).attr("style", "padding: 10px;");
$("#" + TDDeviceTicketID).attr("class", "roundbox1");

This works for removing it JQUERY
$("#" + TDDeviceTicketID).removeAttr("style");
$("#" + TDDeviceTicketID).removeAttr("class");
查看更多
家丑人穷心不美
6楼-- · 2020-07-05 07:40

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"
查看更多
甜甜的少女心
7楼-- · 2020-07-05 07:40

Generally, you can do it directly

document.getElementById("myDiv").style.color = "red";

There's a reference here.

查看更多
登录 后发表回答