有時候我們需要在運行時動態調整樣式表(stylesheet)中某條規則的內容,這可以透過 JavaScript 操作 document.styleSheets 來達成。以下範例使用 underscore 的 find 方法遍歷第四個樣式表的 cssRules,並依選擇器文字比對,動態修改對應規則的樣式屬性:
_.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";
}
});
這裡有一個非常重要的注意事項:在使用 cssRule 時,不能直接用整串文字一次指派 style 屬性,否則不會生效。也就是說,下面的寫法是行不通的:
cssRule.style = " left: 0; position:''; right: 0; top: 0px; z-index: 1031;";
而必須逐一設定個別的樣式屬性,如下所示:
cssRule.style.padding = "0px";
換句話說,要動態修改樣式表規則,正確的做法是針對每個 CSS 屬性(如 padding、top、position 等)分別賦值,才能確實反映到頁面上。掌握這個細節,就能在運行時靈活地微調既有樣式表了。