直接修改element.style只影响行内样式,无法覆盖CSS文件或style块中的规则(除非无!important且优先级更低);需用驼峰命名、带单位赋值;读取时仅返回行内值,查最终样式须用getComputedStyle。
element.style 只影响行内样式JavaScript 修改元素样式最常用的方式是操作 style 属性,但它只读写 HTML 中的 style 行内属性,不会覆盖 CSS 文件或 块里定义的规则,除非那些规则没加 !important 且优先级更低。
常见误操作:以为 el.style.color = 'red' 能让所有文本变红——其实它只对这个 el 生效,且一旦 CSS 里写了 color: blue !important,JS 就会被压制。
style 属性名用驼峰写法:backgroundColor 而不是 background-color
px、em、% 等),el.style.width = 200 无效,得写 el.style.width = '200px'

el.style.xxx 只返回行内设置的值,查不到 CSS 文件里写的;要查最终计算值,得用 getComputedStyle(el).xxx
classList 是切换样式类的推荐方式比起硬编码样式,用 CSS 类 + classList 更可控、更易维护,也天然支持 :hover、@media 等 CSS 能力。
const btn = document.querySelector('#submit');
btn.classList.add('disabled');
btn.classList.remove('active');
btn.classList.toggle('highlight');
btn.classList.contains('disabled'); // true
add() 和 remove() 可一次传多个类名:el.classList.add('a', 'b', 'c')
toggle('cls', boolean) 的第二个参数决定是强制添加还是移除,不传则切换el.className = 'new',会清空所有已有类insertRule
如果需要在运行时生成整条 CSS 规则(比如主题色注入、组件 scoped 样式),不能靠改 style 或 classList,得操作 元素的 sheet。
const style = document.createElement('style');
document.head.appendChild(style);
const sheet = style.sheet;
sheet.insertRule('.theme-dark { color: #fff; background: #111; }', 0);
insertRule(rule, index) 第二个参数是插入位置,0 表示最前,会影响层叠顺序addRule()(已废弃,不建议用)style.textContent,比反复 insertRule 快getComputedStyle 读的是最终生效值,但有陷阱它返回的是浏览器计算后的样式,看似“真实”,但要注意:
width、margin 这些本应是数字的属性,都带单位:getComputedStyle(el).width === '200px'
::before),除非显式传第二个参数:getComputedStyle(el, '::before')
display)在元素 display: none 时可能返回 'none',但其他布局相关属性(如 height)可能返回 '0px' 或空字符串,行为不一致style 直接、即时但脆弱;classList 间接、可复用但需预设类;insertRule 灵活但难调试;getComputedStyle 看似权威,实则受渲染时机和元素状态影响很大。