DIV CSS 佈局教程網

JavaScript 讀寫 CSS 樣式的七種方法整理
編輯:關於JavaScript     

為了日後查閱方便,翻了些資料整理出以下方法,僅限原生 JS。若有疏漏之處歡迎指正。

一、透過 style 物件讀寫行內樣式

每個 DOM 節點都有 style 屬性,它是一個 CSSStyleDeclaration 物件:

 var elm = document.getElementById('test');
elm.style.color = 'black';

注意駝峰命名:CSS 中的 background-color 在 JS 裡要寫成 backgroundColor,font-size 寫成 setProperty 時才用中折線。

二、透過 getAttribute/setAttribute 直接操作 style 屬性

 elm.setAttribute('style', 'color:red;line-height:30px;');
elm.getAttribute('style');
elm.removeAttribute('style');

這種寫法會整段覆寫 style 屬性內容,原有的行內樣式會全部消失,使用時要留意。

三、透過 cssText 與 setProperty/removeProperty

 elm.style.cssText = 'color:red;line-height:30px;';

elm.style.removeProperty('color');
elm.style.setProperty('color', 'green', 'important');

elm.style.cssText = '';   // 快速清空該規則的所有宣告

setProperty 的第三個參數可指定 priority,傳 'important' 等同於在 CSS 中加上 !important;getPropertyPriority() 則可讀回該優先級,有則回傳 "important",無則回傳空字串。

每一條 CSS 規則中,大括號內的宣告部分都是一個 CSSStyleDeclaration 物件,其成員如下:

屬性

  1. cssText:目前規則的所有樣式宣告文字,可讀寫;
  2. length:目前規則包含幾條宣告;
  3. parentRule:包含目前規則的那條規則。

方法

  1. getPropertyPriority():回傳指定宣告的優先級;
  2. getPropertyValue():回傳指定宣告的值;
  3. item(index):回傳指定位置的屬性名,通常用 [index] 更直接;
  4. removeProperty():刪除一條 CSS 屬性,回傳被刪除的值;
  5. setProperty():設定指定的 CSS 屬性,無回傳值。

四、透過 document.styleSheets 操作樣式表

回傳當前頁面所有樣式表的唯讀類陣列,元素為 CSSStyleSheet 物件:

屬性

  1. cssRules:類陣列,元素為樣式表中的 CSS 規則;IE9 以下為 rules;
  2. disabled:開啟或關閉整張樣式表;
  3. ownerNode:回傳樣式表所在的 DOM 節點,通常是 <link> 或 <style>;若樣式表由 @import 引入則為 null;
  4. parentStyleSheet:回傳包含當前樣式表的那張表,頂層樣式表為 null;
  5. type:通常是 text/css;
  6. title:樣式表的 title 值;
  7. href:唯讀,回傳樣式表網址,內嵌 style 節點為 null;
  8. media:表示套用於螢幕、列印或全部,唯讀,預設 screen。

方法:deleteRule() 刪除一條規則、insertRule() 插入新規則(IE9 以下為 addRule()/removeRule())。

 document.styleSheets[0].insertRule('#test:hover{color: white;}', 0);
document.styleSheets[0].deleteRule(0);   // 刪除第一條規則

document.styleSheets[0].cssRules[1].selectorText;   // 回傳選擇器字串
document.styleSheets[0].cssRules[1].cssText;        // 回傳含選擇器的規則字串
document.styleSheets[0].cssRules[1].style.border;
document.styleSheets[0].cssRules[1].style.cssText;  // 回傳該規則的所有宣告

要特別注意跨來源的樣式表無法存取 cssRules,瀏覽器會拋出安全性錯誤。CDN 上的 Bootstrap 就是典型例子,操作前應先用 try/catch 包住或檢查 href 是否同源。

五、用 getComputedStyle 讀取計算後的樣式

第一個參數是 Element,第二個可為 null、空字串或偽元素字串(如 ':before')。回傳一個唯讀的 CSSStyleDeclaration,代表各種規則層疊後的最終結果:

 var color = window.getComputedStyle(elm, ':before').color;
var color = window.getComputedStyle(elm, ':before').getPropertyValue('color');
var color = window.getComputedStyle(elm, null).color;

計算樣式與行內樣式的 CSSStyleDeclaration 有幾點差異:

  1. 計算樣式的屬性唯讀,改它不會生效;
  2. 值是絕對值,百分比、em、pt 等相對單位會全部換算成 px 字串;顏色會以 rgb(r, g, b) 或 rgba(r, g, b, a) 格式回傳;
  3. 不計算複合屬性,要查 marginTop 而非 margin;
  4. 未定義 cssText 屬性;
  5. 某些屬性(如 font-family)的回傳值可能不精確,使用時需留意;
  6. IE9 以下不支援,舊版 IE 的 Element 有 currentStyle 屬性。

六、動態加入樣式表

方式一:建立 <style> 節點

 var style1 = document.createElement('style');
style1.innerHTML = 'body{color:red}#top:hover{background-color: red;color: white;}';
document.head.appendChild(style1);

方式二:加入外部樣式表

 var link1 = document.createElement('link');
link1.setAttribute('rel', 'stylesheet');
link1.setAttribute('type', 'text/css');
link1.setAttribute('href', 'reset-min.css');
document.head.appendChild(link1);

七、用 matchMedia 檢查 media query

各大瀏覽器最新版本(含 IE10+)皆支援,舊環境可用 matchMedia.js 補全。查詢語句範例:

 @media all and (max-device-width: 700px) {
  body { background: #FF0; }
}

window.matchMedia() 接受查詢字串,回傳 MediaQueryList 物件,具兩個屬性:media 回傳查詢字串本身;matches 回傳布林值,表示當前環境是否符合。

 var result = window.matchMedia('(max-width: 700px)');

if (result.matches) {
  console.log('頁面寬度小於等於 700px');
} else {
  console.log('頁面寬度大於 700px');
}

它另有兩個方法用於監聽變化:

 var mql = window.matchMedia("(max-width: 700px)");

mql.addListener(mqCallback);      // 註冊回呼
mql.removeListener(mqCallback);   // 撤銷回呼

function mqCallback(mql) {
  if (mql.matches) {
    // 寬度小於等於 700 像素
  } else {
    // 寬度大於 700 像素
  }
}

較新的標準改用 addEventListener('change', ...)/removeEventListener,與其他 DOM 事件的寫法一致,新專案建議優先採用。

參考資料

MDN:Web API
阮一峰 JavaScript 標準參考:CSS 操作
《JavaScript 權威指南》第六版

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved