insertRule不插入样式元素

时间:2015-03-23 10:24:32

标签: javascript stylesheet

我试图在HTML中添加新的样式元素。我目前正在使用此博客文章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);
&#13;
<div class="red" style="width: 50px; height: 50px;"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 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