為了日後查閱方便,翻了些資料整理出以下方法,僅限原生 JS。若有疏漏之處歡迎指正。
每個 DOM 節點都有 style 屬性,它是一個 CSSStyleDeclaration 物件:
var elm = document.getElementById('test');
elm.style.color = 'black';
注意駝峰命名:CSS 中的 background-color 在 JS 裡要寫成 backgroundColor,font-size 寫成 setProperty 時才用中折線。
elm.setAttribute('style', 'color:red;line-height:30px;');
elm.getAttribute('style');
elm.removeAttribute('style');
這種寫法會整段覆寫 style 屬性內容,原有的行內樣式會全部消失,使用時要留意。
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 物件,其成員如下:
屬性
cssText:目前規則的所有樣式宣告文字,可讀寫;length:目前規則包含幾條宣告;parentRule:包含目前規則的那條規則。方法
getPropertyPriority():回傳指定宣告的優先級;getPropertyValue():回傳指定宣告的值;item(index):回傳指定位置的屬性名,通常用 [index] 更直接;removeProperty():刪除一條 CSS 屬性,回傳被刪除的值;setProperty():設定指定的 CSS 屬性,無回傳值。回傳當前頁面所有樣式表的唯讀類陣列,元素為 CSSStyleSheet 物件:
屬性
cssRules:類陣列,元素為樣式表中的 CSS 規則;IE9 以下為 rules;disabled:開啟或關閉整張樣式表;ownerNode:回傳樣式表所在的 DOM 節點,通常是 <link> 或 <style>;若樣式表由 @import 引入則為 null;parentStyleSheet:回傳包含當前樣式表的那張表,頂層樣式表為 null;type:通常是 text/css;title:樣式表的 title 值;href:唯讀,回傳樣式表網址,內嵌 style 節點為 null;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 是否同源。
第一個參數是 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 有幾點差異:
rgb(r, g, b) 或 rgba(r, g, b, a) 格式回傳;marginTop 而非 margin;方式一:建立 <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);
各大瀏覽器最新版本(含 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 事件的寫法一致,新專案建議優先採用。
參考資料