简体   繁体   中英

Parsing CSS background-image and selector

I need to parse a piece of CSS. Example:

<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>

Which I'd want to convert to the following array:

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

I am interested to match url(IMAGE) and then get its selector(s).

Using JSCSSP

CSS

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

Javascript

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>[^\)]*).+?\})

released on your <script> block would give you a regex that has 2 named groups

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

and for the second match

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

or you can use the "image.png" in your regex to get :

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

to get the result in

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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