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'
});
fontSize),CSS 使用連字號(font-size)el.style.width = '100px')!importantgetComputedStyle 唯讀,無法直接修改優先使用 classList 操作 CSS 類別,將樣式定義在 CSS 檔案中,JS 僅負責狀態切換,符合關注點分離原則。