直接改元素style属性最简单但有局限:只能修改内联样式,css属性需驼峰式,单位必须显式写出;推荐用classlist切换预设类名;读取真实样式用getComputedStyle;批量操作可用CSSStyleSheet.insertRule。

直接改元素的 style 属性最简单但有局限
这是最快上手的方式:获取 dom 元素后,直接赋值 element.style.xxx。比如 element.style.color = 'red' 或 element.style.fontSize = '16px'。
注意点:
-
style只能修改内联样式(即写在 htmlstyle属性里的),无法覆盖外部 CSS 文件或块中带
!important的规则 - CSS 属性名要转成驼峰式:
background-color→backgroundColor,z-index→zIndex - 单位必须显式写出:
element.style.width = '200px',写200会被忽略
用 classList 切换预设 CSS 类更可靠
绝大多数动态样式变更,推荐走「切换类名」路线。先在 CSS 里定义好状态类(如 .is-active、.theme-dark),再用 js 控制开关。
常用方法:
立即学习“Java免费学习笔记(深入)”;
-
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)'
注意:
批量操作建议用 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)删除) - 不兼容 IE9 以下;safari 对跨域样式表有限制
真正难的不是怎么改,而是改完要不要触发重排、动画是否卡顿、样式优先级有没有被意外覆盖——这些往往藏在看似简单的 style.color = 'red' 后面。