萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 設定與移除 HTML 元素樣式屬性

JS 操作元素 style 屬性完整教學

JavaScript 透過 style 屬性直接操作元素內聯樣式,是動態修改外觀的基礎技能。注意:這與「移除 HTML 標籤」不同,是操作 CSS 樣式。

基本操作:設定與讀取

<div id="demo">示範文字</div>

<script>
const el = document.getElementById('demo');

// 設定單一樣式
el.style.fontWeight = 'bold';
el.style.color = '#336699';

// 批次設定(CSSText)
el.style.cssText = 'font-weight: bold; color: #336699; padding: 10px;';

// 讀取計算後樣式(含 CSS 類別)
const computed = window.getComputedStyle(el);
console.log(computed.color); // rgb(51, 102, 153)
</script>

移除樣式的三種方式

<script>
const el = document.getElementById('demo');

// 1. 移除單一屬性
el.style.removeProperty('color');
// 或
el.style.color = '';

// 2. 清空所有內聯樣式
el.style.cssText = '';
// 或
el.removeAttribute('style');

// 3. 切換類別(推薦:關注點分離)
el.classList.add('highlight');
el.classList.remove('highlight');
el.classList.toggle('active');
</script>

實用工具函數

// 設定多樣式物件
function setStyles(el, styles) {
  Object.assign(el.style, styles);
}

// 取得實際顯示樣式
function getStyle(el, prop) {
  return window.getComputedStyle(el)[prop];
}

// 重置為預設
function resetStyle(el, prop) {
  el.style.removeProperty(prop);
}

// 使用範例
setStyles(document.getElementById('box'), {
  width: '200px',
  height: '100px',
  background: 'linear-gradient(45deg, #336699, #66ccff)',
  borderRadius: '8px',
  transition: 'all 0.3s ease'
});

常見誤區

  • 屬性命名:JS 使用駝峰式(fontSize),CSS 使用連字號(font-size)
  • 單位:數值型屬性通常需加單位(el.style.width = '100px')
  • 優先級:內聯樣式 > ID 選擇器 > 類別 > 標籤,慎用 !important
  • getComputedStyle 唯讀,無法直接修改

現代最佳實踐

優先使用 classList 操作 CSS 類別,將樣式定義在 CSS 檔案中,JS 僅負責狀態切換,符合關注點分離原則。

copyright © 萬盛學電腦網 all rights reserved