【问题标题】:insertRule does not insert style elementinsertRule 不插入样式元素
【发布时间】: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 元素,但没有注入样式规则。也没有抛出错误。

当我获取样式表对象时,我看不到 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);
&lt;div class="red" style="width: 50px; height: 50px;"&gt;&lt;/div&gt;

【问题讨论】:

    标签: javascript stylesheet


    【解决方案1】:

    这是因为您传递的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);
    &lt;div class="red" style="width: 50px; height: 50px;"&gt;&lt;/div&gt;

    【讨论】:

    • 但是生成的&lt;style&gt;元素还是空的。为什么是空的?
    • @trusktr 检查样式元素时,带有插入规则的工作表属性会显示在 Chrome 的开发人员工具中:元素 - 属性选项卡。
    • @gabore 谢谢。 :) 我原以为它会更新样式的 CSS 文本内容,但我想性能成本不会很理想。但这意味着如果一段代码依赖于文本内容,而另一段代码不依赖于文本内容,那么它们可能不同步并且可能存在错误。
    【解决方案2】:

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

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

    【讨论】:

    • index 不是必需的。上面的 MDN 链接显示 insertRule 的第二个参数是可选的:stylesheet.insertRule(rule [, index])
    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多