直接操作style属性适合动态设置少量样式;切换className或classList更易维护且支持动画;动态插入CSS规则适用于主题切换等场景;getComputedStyle用于读取最终计算样式。
直接操作元素的 style 属性是最常用、最直观的方式,适合动态设置单个或少量样式;更灵活的场景则推荐用 className 切换预定义 CSS 类,或通过 CSSOM API(如 insertRule)动态增删样式规则。
每个 DOM 元素都有 style 属性,对应其 HTML 中的 style 特性。它是一个 CSSStyleDeclaration 对象,属性名采用驼峰写法(如 backgroundColor 而非 background-color)。
element.style.color = 'red';
element.style.width = '200px';(注意:数字值不会自动加 px)element.style.removeProperty('opacity');
Object.assign(element.style, { opacity: 0.8, transform: 'scale(1.2)' });
比起逐个改 style,预先在 CSS 中定义好类(如 .highlight、.disabled),再用 JS 控制类的增删,更易维护、支持过渡动画、且不影响其他内联样式。
element.className = 'btn btn-primary active';
classList(更安全):element.classList.add('active');、element.classList.remove('disabled');、element.classList.toggle('hidden');
element.classList.contains('error');
element.classList.add('a', 'b'); element.classList.remove('c', 'd');
当需要运行时生成整套样式(比如主题色切换、根据屏幕尺寸注入媒体查询),可操作 标签或 CSSStyleSheet 对象。
标签:const style = document.createElement('style');
style.textContent = '.theme-dark { background: #111; color: #fff; }';
document.head.appendChild(style);const sheet = document.styleSheets[0];
sheet.insertRule('.new-rule { display: none; }', sheet.cssRules.length);
sheet.cssRules[0].style.backgroundColor = '#eee';
修改样式后,若需获取浏览器实际应用的值(含继承、层叠、媒体查询生效后的结果),不能依赖 element.style.xxx(它只返回内联样式),而要用 getComputedStyle。
const computed = getComputedStyle(element);computed.fontSize、computed.getPropertyValue('margin-top')
'16px'),且是只读对象,无法直接修改基本上就这些。选哪种方法取决于你要改的是单个元素还是全局规则、是否需要复用、要不要动画支持——不复杂但容易忽略细节。