- css insertRule 动态插入 参考insertRule
CSSStyleSheet.insertRule()
方法用来给当前样式表插入新的样式规则(CSS rule),并且包含一些限制。
注意:尽管
insertRule()
是 CSSStyleSheet
的一个方法,但它实际插入的地方是 CSSStyleSheet.cssRules
的内部CSSRuleList
。
- 语法:
stylesheet.insertRule(rule [, index])
返回值:新插入的规则在当前样式表规则列表中的索引。
示例:
在样式表顶部插入新的规则
myStyle.insertRule("#blanc { color: white }", 0);
- 实现一个添加样式表规则的函数
/**
* 在文档中添加一条样式表规则(这可能是动态改变 class 名的更好的实现方法,
* 使得 style 样式内容可以保留在真正的样式表中,以斌面添加额外的元素到 DOM 中)。
* 注意这里有必要声明一个数组,因为 ECMAScript 不保证对象按预想的顺序遍历,
* 并且 CSS 也是依赖于顺序的。
* 类型为数组的参数 decls 接受一个 JSON 编译的数组。
* @example
addStylesheetRules([
['h2', // 还接受第二个参数作为数组中的数组
['color', 'red'],
['background-color', 'green', true] // 'true' for !important rules
],
['.myClass',
['background-color', 'yellow']
]
]);
*/
//与官网有改动
function addStylesheetRules(decls, ruleName = null) {
var style = document.createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
if (!window.createPopup) { /* For Safari */
style.appendChild(document.createTextNode(''));
}
var s = document.styleSheets[document.styleSheets.length - 1];
if (ruleName !== null && ruleName.length > 0) {
s.ruleName = ruleName;
}
for (var i = 0, dl = decls.length; i < dl; i++) {
var j = 1, decl = decls[i], selector = decl[0], rulesStr = '';
if (Object.prototype.toString.call(decl[1][0]) === '[object Array]') {
decl = decl[1];
j = 0;
}
for (var rl = decl.length; j < rl; j++) {
var rule = decl[j];
rulesStr += rule[0] + ':' + rule[1] + (rule[2] ? ' !important' : '') + ';\n';
}
if (s.insertRule) {
s.insertRule(selector + '{' + rulesStr + '}', s.cssRules.length);
}
else { /* IE */
s.addRule(selector, rulesStr, -1);
}
}
}
/*
* 从当前样式表中删除指定的样式规则(自己实现,不一定没有问题)
*/
function deleteStylesheetRule(index, ruleName = null) {
if (ruleName === null) return;
let myStyles = Array.from(document.styleSheets).filter(p => p.ruleName === ruleName);
myStyles.forEach(style => {
if (style.cssRules.length > index)
style.deleteRule(index);
});
}
实现效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css insertRule</title>
<script src="./util.js"></script>
</head>
<body>
<div>
<p>css insertRule</p>
<div id="dom_1">测试css insertRule</div>
</div>
<script>
addStylesheetRules([['#dom_1', ['color', "black"], ["background-color", "green"]], ["#dom_1", ['font-size', '2rem'], ['margin', '20px']]],'dom_1');
addStylesheetRules([['#dom_1', ['width', "200px"]]]);
setTimeout(() => {
console.log("delete rules")
deleteStylesheetRule(1,'dom_1');
}, 3000);
</script>
</body>
</html>

插入后的style样式是这样的


注意: 此时的样式表并不能在控制台里面调试,在控制台中显示是灰色的。关于这点说明可以看这里:CSSRuleList。大概的意思就是:CSS 规则列表 CSSRuleList
是一个(只允许间接更改的)类数组对象,包含着一个 CSSRule 对象的有序集合。因为只能间接更改(可更改,但是其本身只拥有读取方法),无法直接往规则列表中添加或移除规则,只能通过它的父样式表进行更改。事实上,.insertRule() 和 .deleteRule() 甚至都不是 CSSRuleList 的方法,而是 CSSStyleSheet 的。
网友评论