insertRule 不插入样式元素

insertRule does not insert style element

我正在尝试向 HTML 添加新的样式元素。我目前正在使用此博客中的代码片段 post http://davidwalsh.name/add-rules-stylesheets

当它在 codepen http://codepen.io/angelathewebdev/pen/vEjNvj?editors=101 中运行时,我看不到样式。注入了一个 style 元素,但是没有注入样式规则。也没有抛出错误。

当我获取样式表对象时,我没有看到 insertRuleaddRule 属性。

 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>

因为index你传递的是越界

对于insertRule你不需要传递索引。

 if("insertRule" in sheet) {
        sheet.insertRule(selector + "{" + rules + "}");

否则通过 0

addCSSRule(style.sheet, '.red', "background: red;", 0);

DEMO

 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;", 0);
<div class="red" style="width: 50px; height: 50px;"></div>

根据 insertRule() 的更新文档,现在需要正式传递 index 参数。你不能离开它。

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule