合并html中某个元素的样式

时间:2022-05-09 20:31:42

当定义很多个样式时,往往在页面中显示优先级高的样式,一些定义的样式就被屏蔽了,所以要合并自定义样式到一个span中,

 protected string MergeStyle(string s)
    {
      
        string pattern = @"(<span[\s\S]*><span[\s\S]*>)[\u4e00-\u9fa5]+(</span></span>)+";
        Regex regex = new Regex(pattern);
        MatchCollection matches = Regex.Matches(s, pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
        foreach (Match m in matches)
        {
            string str = m.ToString();
            string p1 = @"[\u4e00-\u9fa5]+";
            Regex r1 = new Regex(p1);
            Match m1 = r1.Match(str);
            string s1 = m1.ToString();         

            System.Collections.Generic.List<int> al = new System.Collections.Generic.List<int>();
            char[] strChars = str.ToCharArray();
            for (int i = 0; i < strChars.Length; i++)
            {
                if (strChars[i] == '\"')
                {
                    al.Add(i);
                }

            }
            string style = "";
            int tag = 1;
            for (int i = 0; i < al.Count/2; i++)
            {
                if (i == 0)
                {
                  style= str.Substring(al[i] + 1, al[i + 1] - al[i] - 1)+";";
                }
                else {
                style+= str.Substring(al[tag + 1] + 1, al[tag + 2] - al[tag + 1] - 1)+";";
                    tag = tag + 2;

                }

            }
           
            string newStyle = "<span style=\" " + style + "\" >" + s1 + "</span>";
            s = regex.Replace(s, newStyle);

        }


        return s;

    }


目前还有bug,当一些特殊情况就不能合并。在改进中