我正在创建一个 CSSStyleSheet在javascript中。然后我想将样式表 css 导出为文本。
是否有从 CSSStyleSheet
获取 CSS 文本的函数/方法?以下返回一个空字符串:
$('<style id="mystyle"></style>')
.attr('type', 'text/css')
.insertBefore(this.element);
$('#mystyle')[0].sheet.insertRule('#mydiv {color: red;}', 1);
console.log($('#mystyle').html()); // should show '#mydiv {color: red;}'
console.log($('#mystyle').text());
console.log($('#mystyle')[0].innerHTML);
最佳答案
CSSStyleSheet您正在使用的对象为您提供 cssRules
(CSSRuleList 的实例)属性,它是一个类似对象的数组,您可以迭代以提取所有必要的 cssText
字符串。
例如,使用 Array.prototype.reduce 将所有 cssText 聚合到一个字符串中:
$('<style id="mystyle"></style>')
.attr('type', 'text/css')
.appendTo(document.body);
const styleSheet = $('#mystyle')[0].sheet
styleSheet.insertRule('#mydiv {color: red;}');
styleSheet.insertRule('p {color: green;}');
// second argument to insertRule is not needed in our case, but your could do
// styleSheet.insertRule('#mydiv {color: red;}', styleSheet.cssRules.length);
const cssText = Array.from(styleSheet.cssRules).reduce((prev, cssRule) => {
return prev + '\n' + cssRule.cssText
}, '')
console.log(cssText)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv">one</div>
<p>two</p>
关于javascript - 将动态 CSS 导出为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989511/