简体   繁体   English

如何使用Javascript解析@import样式表

[英]How do I parse @import stylesheets with Javascript

I am trying to read CSS selectors in my stylesheets with the document.styleSheets array. 我正在尝试使用document.styleSheets数组在样式表中读取CSS选择器。 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). 它适用于<link><style>标签,但当我在<style>使用@import时它不会出现在数组中 - 仅作为cssRule(样式在Safari 3和FF 3中为“未定义”) )。

So: How can I parse the css in an @imported file? 那么:我如何在@imported文件中解析css?

Assuming that our document contains an @import-rule as first rule in the first stylesheet, here's the code for standards compliant browsers 假设我们的文档在第一个样式表中包含@ import-rule作为第一个规则,这里是符合标准的浏览器的代码

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

and the special case for our all-beloved IE 和我们所有心爱的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... 如果您已经阅读我已经链接到的quirksmode.org的页面,然后使用for..in循环走了@import -rule的属性,那么你可以很容易地想出这个 - 这就是我做的...

PS: I can't comment on other answers yet, but if I could, I would have ridiculed you properly ;) PS:我还不能对其他答案发表评论,但如果可以的话,我会适当地嘲笑你;)

Check this page - which further links to this one on quirksmode.org. 查看此页面 - 在quirksmode.org上进一步链接到此页面。

Thanks, but I have tried that... the Quirksmode examples never parse stylesheets embedded with @import. 谢谢,但我已经尝试过了...... Quirksmode示例从不解析嵌入了@import的样式表。

If I have this HTML/CSS: 如果我有这个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). ...然后document.styleSheets.length为2(链接标记和样式标记)。 The CSS file that is linked through @import will be available as 通过@import链接的CSS文件将以

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

In other words, a CSS rule. 换句话说,CSS规则。 This can also be seen at the Quirksmode page that you mentioned, Christoph. 这也可以在你提到的Quirksmode页面上看到,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)... 我可以得到它的cssText(“@ import url('css / test2.css');”)但我无法弄清楚如何解析文件中的CSS(test2.css)...

If I have totally missed something obvious here, feel free to ridicule me... :) 如果我完全错过了一些明显的东西,请随意嘲笑我...... :)

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

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

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