简体   繁体   English

如何使用cssRule更改全局样式元素的innerHTML?

[英]How do I change the innerHTML of a global style element with cssRule?

This doesn't really require much content as the code itself is self explanatory. 这并不需要太多内容,因为代码本身是自我解释的。 However, just have to escape the condition of writing this context. 但是,只需要逃避编写此上下文的条件。 How do I update the innerHTML of a style element by changing the cssText of the stylesheet's cssRule? 如何通过更改样式表的cssRule的cssText来更新样式元素的innerHTML?

HTML: HTML:

<style>
    body {
        background-color: blue;
    }
</style>

JS: 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; }"

How do I change the innerHTML of the style along with the cssRule? 如何使用cssRule更改样式的innerHTML?

HTML markup is usually meant to be markup , not dynamically-changing non-markup data , as you're using it for in the dynamic stylesheet. HTML标记通常意味着标记 ,而不是动态更改非标记数据 ,因为您在动态样式表中使用它。 If you want the innerHTML to change, you'll have to collect the new text of all the cssRules and explicitly reassign the innerHTML of the style element. 如果您希望更改innerHTML ,则必须收集所有cssRules的新文本并显式重新分配style元素的innerHTML

(similarly, if you reassign a variable inside a script tag, the innerHTML of that script tag doesn't change: (类似地,如果在脚本标记内重新分配变量,则该脚本标记的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> 

Note that you must use sheet.cssRules to get a collection of rules; 请注意,您必须使用sheet.cssRules来获取规则集合; sheet.cssRule will evaluate to undefined . sheet.cssRule将评估为undefined

Because you're retrieving and inserting text into the inside of the style tag, rather than HTML markup, it might be more appropriate to use textContent rather than innerHTML : 因为你检索和插入文本样式标签内,而不是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.

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