2013-09-30 23 views
0

我需要解析一塊CSS。例如:解析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"} 
] 

!我想匹配的網址(IMAGE),然後獲取其選擇器(S)。

+3

HTTP://glazman.o rg/JSCSSP/ – jantimon

+0

你能指望有效的CSS樣式表嗎?或者你必須考慮所有可能性? – avrahamcool

+0

爲什麼不這樣做簡單的方法?看看window.getComputedStyles Javascript方法。不完全是你想要的,但你可以把它包裝在一個修改後的函數中,該函數將包含選擇器... –

回答

0
(?<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" 
0

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