萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取與設置 CSS 樣式完全指南:getComputedStyle、currentStyle、style 屬性差異與最佳實踐

JavaScript 操作 CSS 樣式分為「獲取計算後樣式」與「設置內聯樣式」兩大場景。本文詳解 getComputedStyle(標準)、currentStyle(IE舊版)、element.style(內聯)三者差異,提供跨瀏覽器兼容獲取函數與現代最佳實踐。

三種樣式獲取方式對比

方式代碼獲取範圍返回值瀏覽器支援
內聯樣式el.style.property僅 style="" 內聯屬性字串或空串全瀏覽器
計算樣式 (標準)getComputedStyle(el)[prop]所有樣式表+繼承+默認值解析後絕對值(如 16px)IE9+、所有現代瀏覽器
計算樣式 (IE舊版)el.currentStyle[prop]所有樣式表+繼承+默認值可能為相對值(如 1em)IE6-8

跨瀏覽器兼容獲取函數

var getStyle = function(elementId, property) {
  var el = document.getElementById(elementId);
  if (!el) return null;
  
  // 標準瀏覽器
  if (window.getComputedStyle) {
    return window.getComputedStyle(el, null)[property];
  }
  // IE8-
  else if (el.currentStyle) {
    return el.currentStyle[property];
  }
  // 降級:僅內聯樣式
  return el.style[property];
};

// 使用
var paddingLeft = getStyle('myDiv', 'paddingLeft'); // "16px"
var color = getStyle('myDiv', 'color');             // "rgb(0, 0, 0)"

屬性名稱轉換規則:CSS 中劃線 → JS 駝峰

規則:去掉連字符,後續字母大寫。float 特殊:標準 cssFloat、IE styleFloat。

設置樣式:內聯 style 屬性

// 單個屬性
el.style.paddingLeft = '20px';
el.style.backgroundColor = '#f00';

// 批量設置(現代)
Object.assign(el.style, {
  paddingLeft: '20px',
  backgroundColor: '#f00',
  fontSize: '14px'
});

// cssText 一次性設置(覆蓋所有內聯樣式)
el.style.cssText = 'padding-left:20px; background:#f00; font-size:14px;';

// 獲取 cssText
console.log(el.style.cssText);

特殊屬性處理:float

// 兼容寫法
if ('cssFloat' in el.style) {
  el.style.cssFloat = 'left'; // 標準
} else {
  el.style.styleFloat = 'left'; // IE8-
}

// 統一封裝
function setFloat(el, value) {
  el.style.cssFloat = value;
  el.style.styleFloat = value; // 互不干擾,雙重保險
}

實戰:獲取元素真實幾何尺寸

function getRealSize(el) {
  // 方案一:getBoundingClientRect (推薦,含 transform 縮放)
  var rect = el.getBoundingClientRect();
  return { width: rect.width, height: rect.height };
  
  // 方案二:offsetWidth/Height (含 border、padding、滾動條)
  // return { width: el.offsetWidth, height: el.offsetHeight };
  
  // 方案三:clientWidth/Height (含 padding、不含 border/滾動條)
  // return { width: el.clientWidth, height: el.clientHeight };
}

現代最佳實踐建議

  1. 讀寫分離:讀用 getComputedStyle,寫用 el.style.xxx 或 CSS 類名切換
  2. 避免強制同步佈局:連續「讀寫讀寫」觸發多次重排,批量讀後批量寫
  3. 優先 CSS 類名切換:el.classList.add('highlight') 而非逐條改 style
  4. CSS 變量動態值:el.style.setProperty('--color', 'red') 配合 var(--color)
  5. 動畫用 transform/opacity:不觸發重排,GPU 加速

常見坑點

CSS 屬性JS 屬性 (style/currentStyle/getComputedStyle)
padding-leftpaddingLeft
background-colorbackgroundColor
font-familyfontFamily
z-indexzIndex
border-left-widthborderLeftWidth
問題原因解決
獲取 auto/%/emcurrentStyle 返回原始值用 getComputedStyle 獲取解析後像素值
獲取 display: none 元素尺寸為 0不在渲染樹中臨時 visibility:hidden; position:absolute; display:block 測量
簡寫屬性無法獲取getComputedStyle(el).border 返回空必須獲取長屬性:borderLeftWidth 等
偽類樣式獲取::before 等非元素節點getComputedStyle(el, '::before').content
copyright © 萬盛學電腦網 all rights reserved