DOM 元素樣式來源兩類:
class 屬性關聯 CSS 規則。style 屬性(element.style 對象)直接寫在標簽上。需**完全清除內聯樣式**,保留類樣式。
// 清除所有內聯樣式
element.style.cssText = '';
// 或
element.removeAttribute('style');
cssText = '':設置 style 屬性為空字符串,瀏覽器解析後移除所有 CSS 聲明。removeAttribute('style'):直接移除 style 屬性節點,效果等價。**不要動態修改 CSS 規則**(sheet.cssRules 跨域受限、調試難)。改用**類名切換**:
// 預定義類
// .box-normal { ... }
// .box-highlight { ... }
// .box-disabled { ... }
// JS 切換
element.className = 'box-highlight'; // 替換所有類
element.classList.add('box-highlight'); // 添加單個
element.classList.remove('box-normal'); // 移除單個
element.classList.toggle('box-active'); // 切換
element.classList.replace('box-normal', 'box-highlight'); // 替換指定類
// 只清除 color 和 font-size,保留 display 等
const keep = ['display', 'visibility'];
const style = element.style;
for (let i = style.length - 1; i >= 0; i--) {
const prop = style[i];
if (!keep.includes(prop)) style.removeProperty(prop);
}
https://cdn.example.com/style.css),JS **無法讀取/修改** 其 CSSStyleSheet.cssRules(安全策略)。Access-Control-Allow-Origin: *、或改用類名切換繞過。清除內聯樣式:**element.style.cssText = ''** 或 **element.removeAttribute('style')**。動態樣式管理**首選 classList 切換預定義類**,避免直接操作 style 對象或跨域 CSSOM 修改。