Firefox和IE可以't修改cssRules

Firefox and IE can't modify cssRules

本文关键字:修改 cssRules IE 可以 Firefox      更新时间:2023-09-26

我需要更改现有的全局CSS规则,然后访问文档。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是只读的:

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);

适用于Firefox和其他浏览器。请参见插入规则()和删除规则()。