2020-12-15 02:43:09
JavaScript 动态修改 CSS 样式主要有四种实用方法,涵盖从直接元素操作到样式表规则管理的全流程。以下是具体实现方式及代码示例:
1. 直接修改元素的 style 属性适用于快速调整单个元素的特定样式,优先级高于外部样式表。
const element = document.getElementById('demo');element.style.color = 'red';element.style.backgroundColor = '#f0f0f0';特点:
通过切换 CSS 类名批量应用样式,便于维护和复用。
const element = document.getElementById('demo');// 添加类element.classList.add('active');// 移除类element.classList.remove('inactive');// 切换类element.classList.toggle('highlight');CSS 示例:
.active { color: red; }.highlight { background-color: yellow; }优势:
直接管理样式表规则,包括动态添加、删除和修改规则。
获取样式表和规则// 获取所有样式表const styleSheets = document.styleSheets;// 遍历样式表(外部样式表 href 不为 null)styleSheets.forEach(sheet => { console.log(sheet.href || '内联样式表'); // 获取规则集合(兼容性处理) const rules = sheet.cssRules || sheet.rules; rules.forEach(rule => { console.log(rule.selectorText, rule.cssText); });});动态添加规则const sheet = document.styleSheets[0];const selector = '.new-class';const cssText = 'color: blue; font-size: 20px;';// 标准方法if (sheet.insertRule) { sheet.insertRule(`${selector} { ${cssText} }`, sheet.cssRules.length);} // 旧版 IE 兼容else if (sheet.addRule) { sheet.addRule(selector, cssText, sheet.rules.length);}动态删除规则const sheet = document.styleSheets[0];const index = 0; // 要删除的规则索引if (sheet.deleteRule) { sheet.deleteRule(index);} else if (sheet.removeRule) { sheet.removeRule(index);}注意事项:
通过 JavaScript 修改 CSS 变量值,实现全局样式动态切换。
定义 CSS 变量:root { --primary-color: #3498db; --text-color: #333;}body { color: var(--text-color); background-color: var(--primary-color);}动态修改变量// 设置变量document.documentElement.style.setProperty('--primary-color', '#e74c3c');// 获取变量const color = getComputedStyle(document.documentElement) .getPropertyValue('--primary-color');console.log(color); // 输出修改后的值应用场景:

通过合理选择上述方法,可高效实现动态样式管理,同时兼顾性能与可维护性。