我试图在HTML中添加新的样式元素。我目前正在使用此博客文章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);
&#13;
<div class="red" style="width: 50px; height: 50px;"></div>
&#13;
答案 0 :(得分:0)
这是因为你传递的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>
答案 1 :(得分:0)
根据 insertRule()的更新文档,现在需要正式传递 index 参数。你不能离开它。
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule