我正在尝试将新样式元素添加到 HTML 中。我目前正在使用这篇博客文章中的代码片段 http://davidwalsh.name/add-rules-stylesheets
当它在 codepen 中运行时 http://codepen.io/angelathewebdev/pen/vEjNvj?editors=101 ,我看不到样式。注入(inject)了 style
元素,但未注入(inject)样式规则。也没有抛出错误。
当我获取样式表对象时,我没有看到 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>
最佳答案
这是因为您传递的 index
越界。
对于 insertRule
你不需要传递索引。
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}");
否则传递 0
addCSSRule(style.sheet, '.red', "background: red;", 0);
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>
关于javascript - insertRule 不插入样式元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207849/