js实现css替换
使用 JavaScript 动态替换 CSS
通过 JavaScript 动态修改 CSS 样式可以通过多种方式实现,包括直接操作内联样式、修改类名、替换整个样式表或插入新样式规则。
修改元素的 style 属性
直接操作元素的 style 属性可以快速修改内联样式:
const element = document.getElementById('target');
element.style.color = 'red';
element.style.fontSize = '16px';
这种方法适用于少量样式修改,但会覆盖内联样式表的规则。
切换类名
通过添加或移除 CSS 类实现样式切换:
const element = document.getElementById('target');
element.classList.add('active'); // 添加类
element.classList.remove('inactive'); // 移除类
element.classList.toggle('highlight'); // 切换类
对应的 CSS 需要预先定义:

.active { color: red; }
.inactive { opacity: 0.5; }
.highlight { background: yellow; }
插入样式规则
通过 document.styleSheets 访问和修改现有样式表:
const styleSheet = document.styleSheets[0];
styleSheet.insertRule('.dynamic { color: blue; }', styleSheet.cssRules.length);
或者通过创建新的 <style> 元素插入全局样式:
const style = document.createElement('style');
style.textContent = 'body { background: #f5f5f5; }';
document.head.appendChild(style);
替换整个样式表
通过修改 <link> 元素的 href 属性实现完整样式表切换:

const link = document.querySelector('link[rel="stylesheet"]');
link.href = 'new-styles.css';
这种方法适用于主题切换等需要整体更换样式的场景。
使用 CSSOM 操作样式
通过 CSS Object Model 更精细地控制样式规则:
const style = document.createElement('style');
document.head.appendChild(style);
style.sheet.insertRule('p { font-weight: bold; }', 0);
CSSOM 提供了对样式规则的编程式访问和修改能力。
注意事项
- 直接操作
style属性的优先级最高,会覆盖其他样式规则 - 类名切换方式更易于维护,适合状态驱动的样式变化
- 动态插入的样式规则会影响页面性能,需谨慎使用
- 样式表替换可能导致页面短暂闪烁,可考虑预加载技术






