[英]Adding css class through aspx code behind
I am using aspx.我正在使用 aspx。 If I have HTML as follows:
如果我有 HTML 如下:
<div id="classMe"></div>
I am hoping to dynamically add a css class through the code behind file, ie on Page_Load.我希望通过隐藏文件的代码动态添加 css class,即在 Page_Load 上。 Is it possible?
是否可以?
If you want to add attributes, including the class, you need to set runat="server"
on the tag. 如果要添加包括类在内的属性,则需要在标签上设置
runat="server"
。
<div id="classMe" runat="server"></div>
Then in the code-behind: 然后在后面的代码中:
classMe.Attributes.Add("class", "some-class")
If you're not using the id
for anything other than code-behind reference (since .net mangles the ids), you could use a panel
control and reference it in your codebehind: 如果您没有将
id
用作后台代码引用之外的其他代码(因为.net修改了id),则可以使用panel
控件并在后台代码中引用它:
<asp:panel runat="server" id="classMe"></asp:panel>
classMe.cssClass = "someClass"
Assuming your div has some CSS classes already... 假设您的div已经有一些CSS类...
<div id="classMe" CssClass="first"></div>
The following won't replace existing definitions: 以下内容不会取代现有的定义:
ClassMe.CssClass += " second";
And if you are not sure until the very last moment... 如果您不确定直到最后一刻...
string classes = ClassMe.CssClass;
ClassMe.CssClass += (classes == "") ? "second" : " second";
controlName.CssClass="CSS Class Name";
下面是工作示例
txtBank.CssClass = "csError";
BtnAdd.CssClass = "BtnCss";
BtnCss should be present in your Css File. BtnCss应该存在于您的CSS文件中。
(reference of that Css File name should be added to the aspx if needed) (如果需要,应将该Css文件名的引用添加到aspx中)
Syntax: 句法:
controlName.CssClass="CSS Class Name";
Example: 例:
txtBank.CssClass = "csError";
If you want to retain the existing class, this would work:如果你想保留现有的 class,这会起作用:
string existingClass = classMe.Attributes["class"];
classMe.CssClass = existingClass + " some-class";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.