我已经尝试了几个小时来得到结果,但是失败了,下面,我将把我所做的一切贴出来,希望我能得到一些提示,顺便说一句,谢谢。
从错误信息来看,是的 cssRules 是空的,肯定是错误的!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
外部CSS
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
谢谢你们!
最佳答案
我怀疑您的 JavaScript 在加载样式表之前正在运行。试试这个:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
或者如果你恰好在使用 jQuery,这更通用:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
更新:另一种可能是您正在使用 Chrome 并加载 CSS 跨域或使用 file://
协议(protocol)。 This appears to be a known issue and is not considered a bug.
关于javascript - 如何获取外部样式的cssText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879704/