萬盛學電腦網

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

JavaScript 動態操作 CSS 樣式:駝峰命名規則與 float 特殊處理完整手冊

核心轉換規則

CSS 屬性名 (kebab-case) → JS 樣式屬性 (camelCase):移除連字符,後續字母大寫。

常見屬性映射表

CSS 屬性JS 屬性備註
margin-topmarginTop
border-left-widthborderLeftWidth
z-indexzIndex
font-familyfontFamily
background-colorbackgroundColor
font-sizefontSize
无連字符屬性同名width、height、display、position、left、top、margin、padding、border、color

特殊屬性:float

float 是 JavaScript 保留字,不能直接使用 style.float。


// 兼容寫法
element.style.cssFloat = 'left';      // 標準瀏覽器 (FF, Chrome, Safari, IE8+)
element.style.styleFloat = 'left';    // IE 6-7

// 封裝函數
function setFloat(element, value) {
  element.style.cssFloat = value;
  element.style.styleFloat = value; // 兼容舊 IE
}

// 獲取 (需檢測)
function getFloat(element) {
  return element.style.cssFloat || element.style.styleFloat || '';
}

完整操作示例


const div = document.querySelector('#demo');

// 設置單個屬性
div.style.marginTop = '20px';
div.style.backgroundColor = '#f0f0f0';

// 批量設置 (Object.assign)
Object.assign(div.style, {
  width: '200px',
  height: '100px',
  padding: '10px',
  border: '1px solid #ccc',
  borderRadius: '4px',      // border-radius
  boxShadow: '0 2px 4px rgba(0,0,0,0.1)', // box-shadow
  transition: 'all 0.3s ease' // transition
});

// 獲取計算樣式 (渲染後最終值)
const computed = window.getComputedStyle(div);
console.log(computed.width); // "200px" (含單位)
console.log(computed.getPropertyValue('margin-top')); // "20px"

CSS 自定義屬性 (CSS Variables) 操作


:root {
  --primary-color: #007bff;
  --spacing: 16px;
}

const root = document.documentElement;

// 讀取
const color = getComputedStyle(root).getPropertyValue('--primary-color').trim();

// 設置 (影響全局)
root.style.setProperty('--primary-color', '#28a745');

// 元素級覆蓋
div.style.setProperty('--spacing', '24px');

現代最佳實踐

  1. 類名切換優於行內樣式:element.classList.add('highlight') 而非直接改 style
  2. CSS-in-JS 方案:Styled Components、Emotion、CSS Modules (構建時處理)
  3. 避免頻繁讀寫 style:批量操作用 cssText 或 Object.assign
  4. 動畫用 CSS 類 + transition,而非 JS 逐幀修改
  5. TypeScript 類型支持:React.CSSProperties 提供完整類型提示

避坑指南

  • 數值屬性需帶單位:el.style.width = '100px' (非 100)
  • 複合屬性不可直接賦值:el.style.border = '1px solid red' 可行,但 el.style.borderWidth 更精確
  • style 對象只反映行內樣式,不包含樣式表規則
  • 舊 IE filter 透明度:el.style.filter = 'alpha(opacity=50)'
copyright © 萬盛學電腦網 all rights reserved