直接改元素style属性最简单但有局限:只能修改内联样式,CSS属性需驼峰式,单位必须显式写出;推荐用classList切换预设类名;读取真实样式用getComputedStyle;批量操作可用CSSStyleSheet.insertRule。
style 属性最简单但有局限这是最快上手的方式:获取 DOM 元素后,直接赋值 element.style.xxx。比如 element.style.color = 'red' 或 element.style.fontSize = '16px'。
注意点:
style 只能修改内联样式(即写在 HTML style 属性里的),无法覆盖外部 CSS 文件或 块中带 !important 的规则background-color → backgroundColor,z-index → zIndex
element.style.width = '200px',写 200 会被忽略classList 切换预设 CSS 类更可靠绝大多数动态样式变更,推荐走「切换类名」路线。先在 CSS 里定义好状态类(如 .is-active、.theme-dark),再用 JS 控制开关。
常用方法:
element.classList.add('active') —— 添加类element.classList.remove('active') —— 移除类element.classList.toggle('active') —— 有则删、无则加element.classList.contains('active') —— 判断是否存在优势明显:可复用 CSS、支持伪类(:hover 等)、便于维护、天然支持 CSS 过渡动画。
getComputedStyle 读取真实生效的样式想读取当前元素最终渲染出的颜色、宽高、字体等值,不能依赖 element.style.xxx(它只返回内联值),得用 getComputedStyle:
const el = document.getElementById('box');
const computed = getComputedStyle(el);
console.log(computed.color); // 'rgb(255, 0, 0)'
console.log(computed.fontSize); // '16px'
console.log(computed.getPropertyValue('
background-color')); // 'rgb(255, 255, 255)'
注意:
em 转成 px,颜色转成 rgb())display)在元素未插入文档时可能返回空字符串CSSStyleSheet.insertRule 动态注入规则需要运行时生成一整套新样式(比如主题色切换、暗黑模式开关),可以往 标签里插入规则,比逐个改 style 或切类更灵活:
const style = document.createElement('style');
document.head.appendChild(style);
const sheet = style.sheet;
sheet.insertRule('.btn { background: #007bff; color: white; }', 0);
sheet.insertRule('.btn:hover { background: #0056b3; }', 1);
关键细节:
insertRule(rule, index) 的 index 是插入位置,从 0 开始sheet.cssRules.length 可查数量,用 deleteRule(i) 删除)真正难的不是怎么改,而是改完要不要触发重排、动画是否卡顿、样式优先级有没有被意外覆盖——这些往往藏在看似简单的 style.color = 'red' 后面。