用 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 是 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 皆可)。
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');
document.getElementById('navition').style.cssText = "color:red; font-size:14px;";
注意 cssText 同樣是全量覆寫,會清掉該元素原本所有的行內樣式。若只想改其中幾項,逐條設定或改用 class 更安全。
left、top、width 則會讓瀏覽器重新計算佈局,效能差距明顯。offsetWidth 與寫 style,會反覆觸發重排。把讀取集中在寫入之前,或用 requestAnimationFrame 批次處理。el.style.setProperty('--main-color', '#fff') 與 el.style.getPropertyValue('--main-color')。動態樣式修改不只讓頁面更有互動性,用得好還能提升效率——適時隱藏不需要的內容,能減少不必要的資料往返。但請記得節制使用,過度依賴 JS 操作樣式,會讓樣式邏輯散落在 JS 與 CSS 兩邊,日後維護相當痛苦。