繁体   English   中英

从代码隐藏文件中的 HTML 元素中删除 CSS class 元素

[英]Remove a CSS class from HTML element in the code behind file

我的界面/网络表单上有以下内容:

<div id="mydiv" class="forceHeight" runat="server" />

现在我的代码中有一个条件,如果某种情况属实,我需要从此控件中删除forceHeight class 。 我知道在 C# 你可以使用:

mydiv.CssClass.Replace("forceHeight", ""); 

我不太确定你是如何使用VB做到这一点的? Intellisense 不向我提供此选项?

有什么想法吗?

如何使用 .NET 从控件中删除一个 CSS class

如果一个控件有多个类,您可以通过编辑 class 字符串来删除其中一个类。 这两种方法都需要为 HTML 元素分配一个 ID,以便您可以在后面的代码中定位它。

<asp:Panel ID="mydiv" CssClass="forceHeight class2 class3" runat="server" />

VB.NET

mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim()

C#

mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim();

使用html 通用控制

<div id="mydiv" class="forceHeight class2 class3" runat="server" />

VB.NET

mydiv.Attributes("class") = mydiv.Attributes("class").Replace("forceHeight", "").Trim()

C#

mydiv.Attributes["class"] = mydiv.Attributes["class"].Replace("forceHeight", "").Trim();

可选Trim以删除尾随空格。


如何使用 .NET 从控件中删除所有 CSS 类

VB.NET

mydiv.Attributes.Remove("class")

C#

mydiv.Attributes.Remove("class");

这将从ID="mydiv"的 div 中删除所有 CSS 类

Me.mydiv.Attributes("class") = ""
Me.mydiv.Attributes.Remove("class")

更好,因为它不会留下存根。 它将产生一个更清洁的 HTML 标签。

<div id="mydiv"></div>

如果你用这个,

Me.mydiv.Attributes("class") = ""

它会产生这个

<div id="mydiv" class=""></div><div id="mydiv" class></div>

我发现使用 REGEX 替换更好,因为替换 class 可能作为部分名称存在于其他类中,这会破坏它们。 所以我使用以下扩展方法:

public static void RemoveClass(this WebControl control, string classToRemove)
{
    if (control == null)
        return;

    control.CssClass = Regex.Replace(control.CssClass, @"(^|\s)" + classToRemove + @"($|\s)", " ");
}
mydiv.Attributes["class"] = mydiv.Attributes["class"].ToString().Replace("ClassName","")
mydiv.Attributes("class") = mydiv.Attributes("class").Replace("forceHeight", "")

其他答案对我不起作用。 就像 OP 所说,我没有在IntelliSense中获得myDiv.CssClass

public static void appendCssClass(HtmlGenericControl htmlGenericControl, string cssClassName)
    {
        htmlGenericControl.Attributes.Add("class", 
            htmlGenericControl.Attributes["class"].ToString() + " " + cssClassName);
    }

    public static void removeCssClass(HtmlGenericControl htmlGenericControl, string cssClassName)
    {
        htmlGenericControl.Attributes.Add("class",
                    htmlGenericControl.Attributes["class"].Replace(cssClassName, ""));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM