除了操作元素的 inline style,瀏覽器還允許你直接改寫樣式表裡的規則本身。入口是 document.styleSheets 與其上的 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";
}
});
這裡用 underscore 的 _.find 做遍歷,當然換成原生 Array.prototype.forEach 或 for 迴圈也完全可行。
直覺上你可能會想把整段宣告一次塞進去:
// 這樣寫不會生效 cssRule.style = " left: 0; position:''; right: 0; top: 0px; z-index: 1031;";
cssRule.style 是一個唯讀的 CSSStyleDeclaration 物件,直接賦值不會改動任何宣告。正確做法是逐個屬性設定:
cssRule.style.padding = "0px";
若要一次套用多個屬性,用 setProperty 或 cssText:
cssRule.style.cssText = "left:0; right:0; top:0px; z-index:1031;";
// 或
cssRule.style.setProperty('padding', '0px', 'important');
一是跨來源樣式表。若 <link> 指向其他網域,存取其 cssRules 會拋出安全性錯誤,必須以 try/catch 包住迴圈,否則一個外鏈就讓整段腳本中斷。
二是索引不穩定。document.styleSheets[4] 這種寫死下標的寫法在樣式表數量變動後就會指向錯誤目標,實務上應改用 href 比對或 id 定位。