kli*_*ore 12 javascript css stylesheet
我无法弄清楚我在哪里出错:/.当我运行此代码时,我得到的只是一个空白元素.我似乎无法使用insertRule方法做任何事情(甚至不会产生错误).我错过了什么吗?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script>
var sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
sheet.insertRule("\
#gridContainer {\
width: 100%;\
height: 100%;\
}\
", 0);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
use*_*110 18
它有点令人困惑,但您的代码确实有效,只是您无法在返回的XML树中看到插入的规则.
要验证您的代码是否有效,您可以执行两项测试:
var style = (function() {
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
console.log(style.sheet.cssRules); // length is 0, and no rules
return style;
})();
style.sheet.insertRule('.foo{color:red;}', 0);
console.log(style.sheet.cssRules); // length is 1, rule addedRun Code Online (Sandbox Code Playgroud)
<p class="foo">
I am some text
</p>Run Code Online (Sandbox Code Playgroud)
运行上面的代码段,您可以看到CSS规则确实适用.并且该cssRules属性在控制台中也会发生变化.
当浏览器扩展生成附加到DOM的自定义样式表时,通常会注意到这一点,并且在调试时它们在检查器中显示为空样式表.
| 归档时间: |
|
| 查看次数: |
11818 次 |
| 最近记录: |