2008-09-20 82 views
11

如何更改div的样式(颜色),如下所示?如何以编程方式更改div的样式

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

回答

7

如果你想改变与客户端代码(JavaScript)的股利的颜色在浏览器中运行的,你做的东西像下面这样:在.aspx文件放 :

<script> 
var fooElement = document.getElementById("foo"); 
fooElement.style.color = "red"; //to change the font color 
</script> 
0

该代码片段不说太多 - 如果代码是服务器端你为什么不改变例如那里的HTML元素的类?

2

它看起来像你在写ASP或JSP。我对任何一种语言都不太熟悉,但无论您使用哪种语言,原则都是一样的。

如果您使用的颜色数量有限,那么通常的选项是创建一些类和写入规则集为他们在你的样式表:


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

等。

然后让你的服务器端脚本生成HTML,使CSS比赛:


<div class="important"> 

你当然应该,ensure that the information is available through means other than colour为好。

如果颜色在运行时确定的,那么你就可以生成样式属性:


<div style="background-color: red;"> 
2

你应该设置在CSS的颜色,然后编程方式更改CSS类。例如:

(CSS)

div.Error { 
    color:red; 
} 

(ASP.NET/VB)

<div class='<%=Iif(HasError, "Error", "")%>'> .... </div> 
1

一般情况下,你可以做到这一点直接

的document.getElementById( “myDiv”) .style.color =“red”;

有一个参考here

9

试试这个thees线

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

那么你可以使用例如

myDiv.Style["color"] = "red"; 
4

若y你想直接改变类而不是风格: ie ..用你想要的造型创建另一个类...

myDiv.Attributes["class"] = "otherClassName" 
相关问题