javascript - insertRule 不插入样式元素

标签 javascript stylesheet

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

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

当我获取样式表对象时,我没有看到 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>

关于javascript - insertRule 不插入样式元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207849/

相关文章:

c# - 从 javascript 或代码隐藏 C# 函数 ASP.NET 调用服务器端 C# 函数

javascript - Meteor JS 在服务器发布方法中获取请求的 url

javascript - Angular $resource 未提供正确的数据

javascript - 在 Firefox 中本地存储 XML 文件

jquery - jQuery 中的 HTML 元素和 jQuery 中的 CSS 样式

CSS 问题 - 通过将样式链接到另一个样式来设置(例如字体大小)一组样式的任何方法?

javascript - 如何编辑 Chart.js donut ?

javascript - 使用本地存储在 2 个样式表之间切换(一次切换)

javascript - 如果打印样式表有效,如何通过 Javascript 检测?

css - 在div中居中图片