我有一个样式标签
.first { color: red } .other { color: blue }
然后我在那里改变第一个选择器
style.sheet.cssRules[0].selectorText = '.second'
现在我想获得完整更新的 css 样式
.second { color: red } .other { color: blue }
但我得到的是标签的原始内容,而不是它。
我应该如何修复代码以获得新样式?
var style = document.getElementById('style')
style.sheet.cssRules[0].selectorText = '.second'
console.log(style.textContent)
<style id="style">.first { color: red } .other { color: blue }</style>
<p class="first">First</p>
<p class="second">Second</p>
<p class="other">Other</p>
您可以连接cssText
每个规则的 。
var style = document.getElementById('style')
style.sheet.cssRules[0].selectorText = '.second'
let newStyle = [...style.sheet.cssRules].reduce((acc, curr)=>acc + curr.cssText, "");
console.log(newStyle);
<style id="style">.first { color: red } .other { color: blue }</style>
<p class="first">First</p>
<p class="second">Second</p>
<p class="other">Other</p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句