下面示範如何透過 JavaScript 動態修改已載入的 CSS 規則:
_.find(document.styleSheets[4].cssRules, function(cssRule){
if(cssRule.selectorText && cssRule.selectorText.indexOf(".navbar-fixed-top2") > -1){
cssRule.style.position = "";
cssRule.style.top = "0px";
}
if(cssRule.selectorText && cssRule.selectorText.indexOf("#pageIndi_content, #page1_l1_content, #page_appList") > -1){
cssRule.style.padding = "0px";
}
if(cssRule.selectorText && cssRule.selectorText.indexOf("#page1_index_content") > -1){
cssRule.style.padding = "0px";
}
});
迴圈這裡用了 underscore 的 find。使用 cssRule 時要注意:不能直接用下面的寫法,否則不會生效:
cssRule.style = " left: 0;position:'';right: 0; top: 0px;z-index: 1031;";
只能逐個屬性設定:
cssRule.style.padding = "0px";
關鍵在於透過 document.styleSheets 取得樣式表物件,再遍歷其 cssRules,比對 selectorText 找到目標規則後,逐一修改 style 上的屬性即可達到動態改寫樣式的目的。