繁体   English   中英

解析CSS背景图片和选择器

[英]Parsing CSS background-image and selector

我需要解析一段CSS。 例:

<style ...>
.foo , #bar {
   /*some css code here*/
   background-image: url(image.png);
 }

 p { 
   background: url(image2.png) repeat-x;
   font-size: 1em;
 }

 a {
   font-size: 1.1em;
 }

</style>

我想将其转换为以下数组:

[
 {"selector":".foo , #bar", "bg":"image.png"},
 {"selector":"p", "bg":"image2.png"}
]

我有兴趣匹配url(IMAGE),然后获取其选择器。

使用JSCSSP

的CSS

<textArea id="source"></textArea>
<button id="parse">Parse</button>

Java脚本

var source = document.getElementById("source"),
    ss,
    parser,
    sheet,
    length1,
    index1,
    length2,
    index2,
    myArray,
    cssRule,
    declaration,
    selector,
    bg;

document.getElementById("parse").addEventListener("click", function () {
    ss = source.value;
    parser = new CSSParser();
    sheet = parser.parse(ss, false, true);

    if (sheet) {
        myArray = [];
        for (index1 = 0, length1 = sheet.cssRules.length; index1 < length1; index1 += 1) {
            cssRule = sheet.cssRules[index1];
            selector = cssRule.mSelectorText;
            for (index2 = 0, length2 = cssRule.declarations.length; index2 < length2; index2 += 1) {
                declaration = cssRule.declarations[index2];
                if (declaration.property === "background-image") {
                    bg = declaration.valueText.match(/url\((\S+)\)/i)[1];
                    myArray.push({
                        "selector": selector,
                        "bg": bg
                    });

                    break
                }
            }
        }

        console.log(myArray);
    }
});

jsfiddle

(?<selector>\n.*?)[^{}](\{.+?(?<=url\()(?<image>[^\)]*).+?\})

在您的<script>块上发布的正则表达式将为您提供具有2个命名组的正则表达式

regex.groups("selector") = ".foo, #bar"
regex.groups("image") = "image.png"

第二场比赛

regex.groups("selector") = "P"
regex.groups("image") = "image2.png"

或者您可以在正则表达式中使用“ image.png”来获取:

\n(?<selector>[^{]*?){(?<t>.+)(?<image>image.png)

得到结果

regex.groups("selector") = ".foo, #bar"

暂无
暂无

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

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