DIV CSS 佈局教程網

JavaScript 動態操作 CSS 的規則與實務
編輯:關於JavaScript     

用 JavaScript 動態改變樣式,是做動畫、響應互動、切換主題的基礎能力。這件事看起來簡單,但屬性命名的規則、取值時的相容差異,都有幾個容易踩的細節。

一、寫入樣式的命名規則

沒有連字號的屬性

直接照抄即可:

obj.style.margin = '10px';
obj.style.width  = '200px';
obj.style.left   = '0';
obj.style.position = 'absolute';

含連字號的屬性

去掉連字號,並把連字號後的第一個字母改為大寫( camelCase ):

obj.style.marginTop      = '10px';   // margin-top
obj.style.borderLeftWidth = '1px';   // border-left-width
obj.style.zIndex         = '100';    // z-index
obj.style.fontFamily     = 'Arial';  // font-family

float 的特殊情況

float 是 JavaScript 的保留字,不能寫成 obj.style.float。正確寫法是分開處理:

obj.style.cssFloat   = 'left';    // 標準寫法,Chrome / Firefox / Safari
obj.style.styleFloat = 'left';    // 舊版 IE

二、讀取樣式的兩種情況

讀行內樣式

直接用 obj.style.屬性名,但只能讀到写在 style 屬性裡的值,讀不到外部樣式表或 class 定義的樣式:

<div id="css88" class="ss" style="width:200px; height:200px; background:#333">內容</div>

console.log(document.getElementById('css88').style.width);   // 200px

讀運算後的樣式

要取得實際套用的值(含 class 與外部樣式表),得用 getComputedStyle:

var el = document.getElementById('css88');
var style = window.getComputedStyle(el, null);
console.log(style.width);       // 實際計算後的寬度

舊版 IE 用的是 el.currentStyle["width"],這個差異在現代專案中已不必理會。要注意 getComputedStyle 回傳的是 CSSStyleDeclaration 物件,取值時屬性名要用連字號形式(style.getPropertyValue('margin-top') 或 style.marginTop 皆可)。

三、批量設定樣式

替換 class

document.getElementById('ceil').className = "class1";
document.getElementById('ceil').className = "class1 class2 class3";

直接指派 className 會整個覆蓋原本的 class。若要追加或移除而不影響其他,請用 classList:

el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('open');

用 cssText 一次寫入多條

document.getElementById('navition').style.cssText = "color:red; font-size:14px;";

注意 cssText 同樣是全量覆寫,會清掉該元素原本所有的行內樣式。若只想改其中幾項,逐條設定或改用 class 更安全。

實務建議

  • 能改 class 就别改 style。把樣式寫在 CSS 裡、用 classList 切換,關注分離得乾淨,也能享受 CSS 的 transition 與 animation。直接改 style 逐格跳動,動畫不會順。
  • 動畫請用 transform 與 opacity。這兩個屬性只觸發合成,不引起重排;改 left、top、width 則會讓瀏覽器重新計算佈局,效能差距明顯。
  • 頻繁讀寫會造成強制同步佈局。在迴圈裡交替讀 offsetWidth 與寫 style,會反覆觸發重排。把讀取集中在寫入之前,或用 requestAnimationFrame 批次處理。
  • 自訂屬性用 setProperty。讀寫 CSS 變數時:el.style.setProperty('--main-color', '#fff') 與 el.style.getPropertyValue('--main-color')。
  • 顯示與隱藏優先用 hidden 屬性。它語意明確,也便於 CSS 統一控制。

動態樣式修改不只讓頁面更有互動性,用得好還能提升效率——適時隱藏不需要的內容,能減少不必要的資料往返。但請記得節制使用,過度依賴 JS 操作樣式,會讓樣式邏輯散落在 JS 與 CSS 兩邊,日後維護相當痛苦。

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