[英]How do I change the innerHTML of a global style element with cssRule?
这并不需要太多内容,因为代码本身是自我解释的。 但是,只需要逃避编写此上下文的条件。 如何通过更改样式表的cssRule的cssText来更新样式元素的innerHTML?
HTML:
<style>
body {
background-color: blue;
}
</style>
JS:
var style = document.getElementsByTagName('style')[0];
var sheet = style.sheet;
sheet.cssRules[0].style.backgroundColor = 'green'; // body changes to green.
sheet.cssRules[0].cssText; // returns "body { background-color: green; }"
style.innerHTML; // returns "body { backgrounds color: blue; }"
如何使用cssRule更改样式的innerHTML?
HTML标记通常意味着标记 ,而不是动态更改非标记数据 ,因为您在动态样式表中使用它。 如果您希望更改innerHTML
,则必须收集所有cssRules
的新文本并显式重新分配style
元素的innerHTML
。
(类似地,如果在脚本标记内重新分配变量,则该脚本标记的innerHTML
不会更改:
let foo = 5; foo = 7; console.log(document.currentScript.innerHTML);
)
<style data-st="st"> body { background-color: blue; } </style> <script> var style = document.querySelector('style[data-st="st"]'); var sheet = style.sheet; sheet.cssRules[0].style.backgroundColor = 'green'; const newFullText = [...sheet.cssRules] .map(({ cssText }) => cssText) .join('\\n'); style.innerHTML = newFullText; console.log(style.innerHTML); </script>
请注意,您必须使用sheet.cssRules
来获取规则集合; sheet.cssRule
将评估为undefined
。
因为你检索和插入文本样式标签内,而不是HTML标记,它可能更适合使用textContent
,而非innerHTML
:
<style data-st="st"> body { background-color: blue; } </style> <script> var style = document.querySelector('style[data-st="st"]'); var sheet = style.sheet; sheet.cssRules[0].style.backgroundColor = 'green'; const newFullText = [...sheet.cssRules] .map(({ cssText }) => cssText) .join('\\n'); style.textContent = newFullText; console.log(style.textContent); </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.