通过 JavaScript 删除 CSS 规则
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29927992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove CSS rules by JavaScript
提问by Ginpei
How to remove CSS rules by JavaScript?
如何通过 JavaScript 删除 CSS 规则?
var elStyle = document.querySelector('style#the-style');
var stylesheet = elStyle.sheet;
var rules = stylesheet.cssRules;
for (var i=0; i<rules.length; i++) {
var rule = rules[i];
if (rule.selectorText === '#rule2 em') {
// TODO: remove this rule
break;
}
}
I succeeded to remove the style by rule.style.color=''
but the rule still exists. Are there any APIs to remove? Or should I use innerHTML
?
我成功地删除了样式,rule.style.color=''
但规则仍然存在。是否有任何要删除的 API?还是我应该使用innerHTML
?
UPDATE
更新
In this case, I'd like to remove style rules, not style properties.
在这种情况下,我想删除样式规则,而不是样式属性。
(I don't know about Stack Overflow's rule well. I hope this editing was right.)
(我不太了解 Stack Overflow 的规则。我希望这个编辑是正确的。)
采纳答案by vasilenicusor
here is an example how you can do this:
这是一个如何执行此操作的示例:
var styleTag = document.getElementById ("the-style");
var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;
if (sheet.cssRules) { // all browsers, except IE before version 9
for (var i=0; i<sheet.cssRules.length; i++) {
if (sheet.cssRules[i].selectorText === '#rule2 em') {
//console.log(sheet.cssRules[i]);
sheet.deleteRule (i);
}
}
}
else
{ // Internet Explorer before version 9
for (var i=0; i<sheet.rules.length; i++) {
if (sheet.rules[i].selectorText === '#rule2 em') {
// console.log(sheet.cssRules[i]);
sheet.removeRule (i);
}
}
}
And on JSFiddle http://jsfiddle.net/n53u7cvm/1/
在 JSFiddle http://jsfiddle.net/n53u7cvm/1/
回答by Fenton
While it is possible to edit the stylesheet programatically, it comes with a host of browser problems.
虽然可以通过编程方式编辑样式表,但它会带来许多浏览器问题。
Here is how you obtain the rules from a stylesheet:
以下是从样式表获取规则的方法:
var rules = new Array();
if (document.styleSheets[1].cssRules) {
rules = document.styleSheets[1].cssRules;
}
else if (document.styleSheets[1].rules) {
rules = document.styleSheets[1].rules;
}
And if you think that's a bit nasty, it gets worse from there!
如果您认为这有点令人讨厌,那么情况会变得更糟!
Update
更新
I can see the question has been edited...
我可以看到问题已被编辑...
The following works (updated JSFiddle)...
以下作品(更新的 JSFiddle)...
if (selector === '#rule2 em') {
rule.style.color = 'black';
}