简体   繁体   English

使用javascript访问外部CSS的内容

[英]Access content of external css using javascript

Its easy to get the internal css code like: 容易获得内部CSS代码,例如:

var css = '';
$('style').each(function(){
     css+=$(this).html();
});

Now if there is an external link for a css file like: 现在,如果有css文件的外部链接,例如:

<link href="style.css" />

Is there anyway to know what css codes are available using javascript/jquery? 无论如何,有什么可以知道使用javascript / jquery可以使用哪些CSS代码?

Is there anyway to know what css codes are available using javascript/jquery? 无论如何,有什么可以知道使用javascript / jquery可以使用哪些CSS代码?

Yes. 是。 There is a styleSheets collection containing StyleSheet objects, most of which will be CSSStyleSheet objects , which have a cssRules property (just rules on old IE) which is a CSSRuleList containing CSSRule objects. 有一个styleSheets集合,其中包含StyleSheet对象,其中大多数将是CSSStyleSheet对象 ,它们具有cssRules属性(仅是旧IE上的rules ),该CSSRuleList包含CSSRule对象的CSSRule It doesn't matter whether the styleshet is external (via link ) or inline (via style ). 样式表是外部的(通过link )还是内联的(通过style )都没有关系。

Example: 例:

 var forEach = Array.prototype.forEach; forEach.call(document.styleSheets, function(sheet, index) { if (sheet.cssRules || sheet.rules) { log("Sheet #" + index); forEach.call(sheet.cssRules || css.rules, function(rule, ri) { log("- Rule #" + ri + ": " + rule.cssText); }); } else { log("Sheet #" + index + " is not a CSSStyleSheet"); } }); function log(msg) { var p = document.createElement('pre'); p.appendChild( document.createTextNode(msg) ); document.body.appendChild(p); } 
 .foo { color: blue; } .bar { color: red; } pre { margin: 0; } 

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

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