Firefox 和 IE 无法修改 cssRules

use*_*123 5 javascript css firefox internet-explorer cross-browser

我需要更改现有的全局 CSS 规则,然后访问document.styleSheets,获取我的规则并修改它。

我通过访问selectorText属性来修改选择

CSS代码

<style type="text/css">
    .class {
        color: #230020;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

我的问题是在所有版本的 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.
Run Code Online (Sandbox Code Playgroud)

如何让它在 Mozilla Firefox、Microsoft Internet Explorer 和 Edge 上运行?

sky*_*000 5

根据MDNselectorText是只读的:

CSSRule.selectorText 属性获取规则集选择器的文本表示。这是以只读方式实现的;要动态设置样式表规则,请参阅使用动态样式信息。

不幸的是,似乎没有一种跨浏览器的方式来更改 CSS 规则的选择器。如果这是您的目标,您可以尝试删除整个规则并使用相同的规则索引将其替换为新规则,您只需要包含所有规则属性以及选择器,如下所示:

var cssText = document.styleSheets[1].cssRules[0].style.cssText;
document.styleSheets[0].deleteRule(0);
document.styleSheets[0].insertRule('.another-class { ' + cssText + ' }', 0);
Run Code Online (Sandbox Code Playgroud)

在 Firefox 和其他浏览器中对我有用。请参阅insertRule()deleteRule()