简体   繁体   中英

How do I parse @import stylesheets with Javascript

I am trying to read CSS selectors in my stylesheets with the document.styleSheets array. It works fine with <link> and <style> tags, but when I use @import inside a <style> it doesn't show up in the array - only as a cssRule (style is "Undefined" in Safari 3 and FF 3).

So: How can I parse the css in an @imported file?

Assuming that our document contains an @import-rule as first rule in the first stylesheet, here's the code for standards compliant browsers

document.styleSheets[0].cssRules[0].styleSheet.cssRules;

and the special case for our all-beloved IE

document.styleSheets[0].imports[0].rules;

You could have easily figured this out yourself if you had read the page at quirksmode.org to which I had already linked and then walked the properties of the @import -rule with a for..in loop - that's what I did...

PS: I can't comment on other answers yet, but if I could, I would have ridiculed you properly ;)

Check this page - which further links to this one on quirksmode.org.

Thanks, but I have tried that... the Quirksmode examples never parse stylesheets embedded with @import.

If I have this HTML/CSS:

<link rel="stylesheet" type="text/css" href="css/test1.css" />

<style type="text/css">

    @import url('css/test2.css');

    div {
        color: blue;
    }

</style>

... then document.styleSheets.length is 2 (the link tag and the style tag). The CSS file that is linked through @import will be available as

document.styleSheets[1].cssRules[0]. 

In other words, a CSS rule. This can also be seen at the Quirksmode page that you mentioned, Christoph. I can get its cssText ("@import url('css/test2.css');") but I can't figure out how to parse the CSS inside the file (test2.css)...

If I have totally missed something obvious here, feel free to ridicule me... :)

优秀的页面,包含大量样式表解析信息: http//www.howtocreate.co.uk/tutorials/javascript/domstylesheets

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