2
我需要更改現有的全局CSS規則,然後訪問document.styleSheets,獲取我的規則並對其進行修改。Firefox和IE無法修改cssRules
我通過訪問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?
我已經更新了我的答案,以向您展示如何緩存原始樣式屬性,以便您不必重新編寫它們。 – skyline3000
這是正確的答案,謝謝。 – user123123123
這是不準確的 - 檢查[spec](https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSRule)。 FF錯誤仍然存在,不過據說它在IE中工作時有警告。我糾正了MDN文章。 – Semicolon