CSS类添加到一个div在后面的代码 [英] Add CSS class to a div in code behind

查看:184
本文介绍了CSS类添加到一个div在后面的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,我想一个CSS类添加到它的代码,但我收到以下错误,当我尝试

I have a div and I am trying to add a CSS class to it in code but I receive the following error when I try

Property or indexer 'System.Web.UI.HtmlControls.HtmlControl.Style' cannot be assigned to -- it is read only

我使用下面的代码:

protected void BTNEvent_Click(object sender, ImageClickEventArgs e)
{
    BtnventCss.Style= "hom_but_a";                 
}



谁能帮帮我吗?

Can anyone please help me?

推荐答案

如果:

 <asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />

要添加或删除一个类
,而不是用

To add or remove a class instead of overwrite all classes with

   BtnventCss.CssClass = "hom_but_a"

保持正确的HTML:

    string classname = "TestClass";
    // add a class
    BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       );
     //remove a class
     BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       );

这确保了


  • 原来的类名保持

  • 有没有双类名

  • 没有disturning多余的空格

特别是当客户端开发,使用一元几类名。

Especially when client-side development is using several classnames on one element.

在您的例子中使用

   string classname = "TestClass";
    // add a class
    Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       ));
     //remove a class
     Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       ));

您应该在方法/属性包装这个;)

You should wrap this in a method/property ;)

这篇关于CSS类添加到一个div在后面的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆