【问题标题】:Setting a class for a DIV that is a server control为作为服务器控件的 DIV 设置一个类
【发布时间】:2010-10-12 01:49:40
【问题描述】:

我有不同的 CSS 样式,其中之一是:

#layoutsectiondiv{
    border: 2px dashed #000000; 
   padding: 1px;
    left: 0px;
}

我有一个 aspx 页面:

<div id="testDiv" runat="server">

</div>

如果是普通的 HTML,我会通过

来设置 div 的样式
<div id="layoutsectiondiv">

</div>

在运行时(在代码后面),我需要为 DIV 动态分配不同的样式。我该怎么做?

【问题讨论】:

    标签: asp.net css


    【解决方案1】:

    使用 class 属性并更改您的 css 样式以使用类选择器而不是 id 选择器。例如

    .layoutsectiondiv{}
    
    <div id="testDiv" class="layoutsectiondiv">
    </div>
    

    编辑

    只创建你的类,以便你将它应用到你想要的特定 div 上。不要重用你的课程。这应该很容易,因为您的 css 已经绑定到特定 ID,只需将该类放在该元素上即可。

    如果您在多种类型的元素上使用该类,您建议的效果会很好。

    【讨论】:

    • css ID 选择器和 asp.net 不能很好地混合,因为 .net 在运行时管理/破坏 ID。
    • 如果我使用类选择器,我如何确保它只能应用于这个 DIV?我想我可以通过执行以下操作来限制对任何 DIV 的使用: div.layoutsectiondiv {} 正确吗?
    【解决方案2】:

    Josh 是对的,你应该使用 class 而不是 id。

    你的问题:

    在运行时(在代码后面),我需要 动态分配不同的样式 分区。我该怎么做?

    试试这个:

    // layoutsectiondiv is defined as class : .layoutsectiondiv{}
    testDiv.Attributes["class"] = "layoutsectiondiv";
    

    【讨论】:

    • 如果我使用类选择器,我如何确保它只能应用于这个 DIV?我想我可以通过执行以下操作来限制对任何 DIV 的使用: div.layoutsectiondiv {} 正确吗?
    • 是的,div.layoutsectiondiv {} 限制了 'layoutsectiondiv' id 仅由 div 使用。但是如果你想让样式只应用你想要的 div,也许你应该使用 style 属性?
    【解决方案3】:

    所以你可以通过这种方式使用 css id 选择器。

    #layoutsectiondiv { color: red }
    

    使用以下html

    <div id="layoutsectiondiv">    
    </div>
    

    或者像这样的 css 类 html 选择器。

    .layoutsectiondiv { color: blue }
    

    使用以下html

    <div class="layoutsectiondiv">
    </div>
    

    如果您想控制特定 .net 控件的样式,即具有 runat="server" 属性的控件,那么我们知道 .net 会“修改”id 以确保其唯一性。

    在这种情况下,在我们的代码中,我们可以使用 FindControl 来访问 div 并更改其样式

    <div id="testDiv" runat="server">
    </div>
    

    即。

            HtmlGenericControl testDiv =
                (HtmlGenericControl)Page.FindControl("testDiv");
    
            // to hide
            testDiv.Attributes.Add("style", "display: none");  // OR
            testDiv.Attributes["style"] = "display: none";
    
            // to show
            testDiv.Attributes.Add("style", "display: block"); // OR
            testDiv.Attributes["style"] = "display: block";
    
            // or to add a class
            testDiv.Attributes.Add("class", "MyCssClassName"); // OR
            testDiv.Attributes["class"] = "MyCssClassName";
    

    这里很好地解释了 css id 和 class 之间的区别 - CSS: div id VS. div class

    这里是How to edit CSS style of a div using C# in .NET

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2015-12-11
      • 2011-05-05
      • 2013-02-09
      • 2013-12-24
      • 2017-10-18
      相关资源
      最近更新 更多