【发布时间】:2015-03-23 10:24:31
【问题描述】:
我正在尝试将新样式元素添加到 HTML 中。我目前正在使用这篇博文中的代码 sn-ps http://davidwalsh.name/add-rules-stylesheets
当它在 codepen http://codepen.io/angelathewebdev/pen/vEjNvj?editors=101 中运行时,我看不到样式。注入了style 元素,但没有注入样式规则。也没有抛出错误。
当我获取样式表对象时,我看不到 insertRule 或 addRule 属性。
function addCSSRule(sheet, selector, rules, index) {
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}", index);
} else if("addRule" in sheet) {
sheet.addRule(selector, rules, index);
}
}
var style = document.createElement('style');
// WebKit hack :(
style.appendChild(document.createTextNode(''));
// Add the <style> element to the page
document.head.appendChild(style);
// Stylesheet Rules
addCSSRule(style.sheet, '.red', "background: red;", 1);
<div class="red" style="width: 50px; height: 50px;"></div>
【问题讨论】:
标签: javascript stylesheet