CSS 通过后面的aspx代码添加css类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1903513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding css class through aspx code behind
提问by DanDan
I am using aspx. If I have HTML as follows:
我正在使用 aspx。如果我有如下 HTML:
<div id="classMe"></div>
I am hoping to dynamically add a css class through the code behind file, ie on Page_Load. Is it possible?
我希望通过文件背后的代码动态添加一个 css 类,即在 Page_Load 上。是否可以?
回答by Chris Haas
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")
回答by Jason
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"
回答by Marc.2377
Assuming your divhas 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";
回答by Anwar
controlName.CssClass="CSS Class Name";
working example follows below
工作示例如下
txtBank.CssClass = "csError";
回答by Veerendranath Darsi
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)
回答by Kishor Makwana
Syntax:
句法:
controlName.CssClass="CSS Class Name";
Example:
例子:
txtBank.CssClass = "csError";