从code更改CSS类的最佳方法 [英] Best way to change CSS Classes from code

查看:178
本文介绍了从code更改CSS类的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是很容易设置的CssClass在codebehind,但这种运行覆盖现有类的风险。

It's easy to set CSSClass in the codebehind, but this runs the risk of overwriting existing classes.

我需要某些元素设置为只读= TRUE;并希望我套用样式为视觉提示,该项目无法改变......很容易

I need to set certain elements to ReadOnly = true; and i'd like to apply a style as a visual cue that the item cannot be altered... easy enough

.CSSClass + =ReadOnlyStyle;

.CSSClass += " ReadOnlyStyle";

但我同样需要将相同的元素改为只读= FALSE;所以我需要删除我设置的CssClass,没有杀死可能被应用于任何其他样式。

But then I equally need to change the same element to ReadOnly = false; so I need to remove the CSSClass i set, without killing off any other styles that might be applied.

什么是做到这一点的最好方法是什么?

What's the best way to do this?

推荐答案

我已经采取AnthonyWJones原来的code和修改它,这样它的作品无论什么情况:

I've taken AnthonyWJones original code and amended it so that it works no matter what scenario:

static class WebControlsExtensions
    {
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Add(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }

        public static void RemoveCssClass(this WebControl control, string cssClass)
        {
            List<string> classes = control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

            classes.Remove(cssClass);

            control.CssClass = classes.ToDelimitedString(" ");
        }
    }

    static class StringExtensions
    {
        public static string ToDelimitedString(this IEnumerable<string> list, string delimiter)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string item in list)
            {
                if (sb.Length > 0)
                    sb.Append(delimiter);

                sb.Append(item);
            }

            return sb.ToString();
        }
    }

这篇关于从code更改CSS类的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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