【问题标题】:How to add an additional css class from code behind using ASP.NET?如何使用 ASP.NET 从后面的代码中添加一个额外的 css 类?
【发布时间】:2014-09-29 10:40:16
【问题描述】:

如何使用 ASP.NET 从代码中添加额外的 css 类?

当前文本框

<asp:TextBox ID="txt" CssClass="MyClass" runat="Server" />

期望的输出

<asp:TextBox ID="txt" CssClass="MyClass Error" runat="Server" />

测试

txt.CssClass = "Error"

这将替换当前的 css 类。

txt.CssClass = "MyClass Error"

这可行,但必须指定类非常低效。

txt.Attributes.Add("class", "Error")

这只有在没有设置初始类时才有效。

txt.Attributes("class") += " Error"

这对我不起作用。

【问题讨论】:

  • txt.CssClass = txt.CssClass + " Error".
  • 或者 txt.CssClass += " Error" 可能会起作用
  • @mikey 我也这么认为,但现在无法测试。
  • @MelanciaUK 是的,这里也一样;)这就是我选择“也许”的原因
  • 把它交给 Rob W,他所链接的实用方法更加健壮。我想在处理字符串连接时可能会变得非常沮丧,而辅助方法有助于防止重复

标签: c# html css asp.net vb.net


【解决方案1】:

像这样添加额外的 CssClass:

txt.CssClass = txt.CssClass + " Error"

以上也可以简写为:

txt.CssClass += " Error"

【讨论】:

    【解决方案2】:

    我知道您正在寻找一个快速的单线。但是,这个先前的答案可能会被证明是有用的:

    How to add more than 1 class to an element in ASP.NET?

    【讨论】:

      猜你喜欢
      • 2011-11-21
      • 2012-08-25
      • 2013-06-13
      • 2013-03-08
      • 2012-03-15
      • 2014-01-18
      • 1970-01-01
      • 2010-12-26
      • 2011-11-26
      相关资源
      最近更新 更多