Firefox 和 IE 无法修改 cssRules
Firefox and IE can't modify cssRules
我需要更改现有的全局 CSS 规则,然后我访问 document.styleSheets,获取我的规则并进行修改。
我通过访问 selectorText 属性.
修改选择器
CSS代码
<style type="text/css">
.class {
color: #230020;
}
</style>
JavaScript代码
var rule = document.styleSheets[0].cssRules[0]; // obtain the first rule.
/* Chrome, Opera, Safari */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".another-class", then it works and the rule changed.
我的问题是,在所有版本的 Firefox 和 Internet Explorer 中,属性 selectorText 似乎是只读的。
/* Internet Explorer, Edge, and Firefox */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".class", It remains as it was.
如何让它在 Mozilla Firefox、Microsoft Internet Explorer 和 Edge 上运行?
根据 MDN,selectorText
是只读的:
The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is implemented in a readonly manner; to set stylesheet rules dynamically, see Using dynamic styling information.
不幸的是,似乎没有跨浏览器的方法来更改 CSS 规则的选择器。如果那是你的目标,你可以尝试删除整个规则并使用相同的规则索引用新规则替换它,你只需要包括所有规则属性以及选择器,如下所示:
var cssText = document.styleSheets[1].cssRules[0].style.cssText;
document.styleSheets[0].deleteRule(0);
document.styleSheets[0].insertRule('.another-class { ' + cssText + ' }', 0);
适用于 Firefox 和其他浏览器。参见 insertRule() and deleteRule()。
我需要更改现有的全局 CSS 规则,然后我访问 document.styleSheets,获取我的规则并进行修改。
我通过访问 selectorText 属性.
修改选择器CSS代码
<style type="text/css">
.class {
color: #230020;
}
</style>
JavaScript代码
var rule = document.styleSheets[0].cssRules[0]; // obtain the first rule.
/* Chrome, Opera, Safari */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".another-class", then it works and the rule changed.
我的问题是,在所有版本的 Firefox 和 Internet Explorer 中,属性 selectorText 似乎是只读的。
/* Internet Explorer, Edge, and Firefox */
rule.selectorText; // returns ".class"
rule.selectorText = ".another-class";
rule.selectorText; // returns ".class", It remains as it was.
如何让它在 Mozilla Firefox、Microsoft Internet Explorer 和 Edge 上运行?
根据 MDN,selectorText
是只读的:
The CSSRule.selectorText property gets the textual representation of the selector for the rule set. This is implemented in a readonly manner; to set stylesheet rules dynamically, see Using dynamic styling information.
不幸的是,似乎没有跨浏览器的方法来更改 CSS 规则的选择器。如果那是你的目标,你可以尝试删除整个规则并使用相同的规则索引用新规则替换它,你只需要包括所有规则属性以及选择器,如下所示:
var cssText = document.styleSheets[1].cssRules[0].style.cssText;
document.styleSheets[0].deleteRule(0);
document.styleSheets[0].insertRule('.another-class { ' + cssText + ' }', 0);
适用于 Firefox 和其他浏览器。参见 insertRule() and deleteRule()。