

新闻资讯
技术学院最直接的方式是用 document.querySelector 定位元素后通过 style 属性修改内联样式,但仅影响行内样式;批量操作用 querySelectorAll 配合 forEach;修改单个样式需用驼峰命名(如 backgroundColor);设置 display: none 后 getComputedStyle 将返回该值而非原始 CSS 值;推荐优先使用 classList.add/remove/toggle 切换预设类名以提升可维护性;动态注入样式规则需通过 CSSStyleSheet.insertRule;监听真实渲染样式变化应使用 getComputedStyle 或 MutationObserver 监控 class 属性。
document.querySelector 找元素再改 style 属性这是最直接的方式:先用 CSS 选择器定位元素,再通过 JS 修改其内联样式。注意它只影响 style 属性,不改变 CSS 类或外部样式表。
document.querySelector 只返回第一个匹配元素;要批量操作,用 document.querySelectorAll 配合 forEach
element.style.propertyName = "value",属性名是驼峰式(如 backgroundColor),不是短横线(background-color)display: none 时,别写成 element.style.display = "none" 后又期望用 getComputedStyle 读取原始值——内联样式优先级更高,会覆盖 CSS 文件里的定义const btn = document.querySelector('button.primary');
btn.style.backgroundColor = '#007bff';
btn.style.borderRadius = '4px';
classList 切换预设的 CSS 类更安全比起硬编码样式值,通过增删 class 来控制样式更易维护、可复用,也避免内联样式污染和优先级混乱。
element.classList.add('active')、.remove('disabled')、.toggle('hidden') 是最常用方法el.classList.add('a', 'b', 'c')
el.classList.contains('loading'),比解析 className 字符串可靠!important,JS 用 style 直接赋值可能被忽略;而 classList 不受此影响,因为它只是开关类名const card = document.querySelector('.card[data-id="123"]');
card.classList.toggle('expanded');
CSSStyleSheet.insertRule
当需要运行时注入整套规则(比如主题色切换、响应式断点适配),不能只靠改单个元素样式,得操作样式表本身。
CSSStyleSheet 对象,通常从 document.styleSheets[0] 或新建 标签中取insertRule 第一个参数是完整 CSS 规则字符串,第二个是插入位置索引(如 0 表示最前)DOMException 错误,建议用 try/catch
deleteRule(index),但要注意索引会随插入/删除变化,最好记录 rule 的引用或用 cssRules 查找const style = document.createElement('style');
document.head.appendChild(style);
const sheet = style.sheet;
sheet.insertRule('.theme-dark .text { color: #f0f0f0; }', 0);
style
属性,用 MutationObserver 或 getComputedStyle
element.style 只反映内联样式,无法感知类名变更或外部 CSS 生效结果。真要响应“最终渲染样式”变化,得另想办法。
getComputedStyle(element) 返回实时计算后的样式对象,适合读取(如判断是否可见、当前宽度),但它是只读的MutationObserver 监控 class 属性:attributes: true, attributeFilter: ['class']
getComputedStyle 某属性(性能差),或在 JS 控制类名/样式前主动触发自定义事件getComputedStyle 返回的值是解析后单位(如 "20px"),不是原始声明值(如 "2rem")const el = document.querySelector('.box');
const computed = getComputedStyle(el);
console.log(computed.width); // "200px"
CSS 选择器和 JS 结合的关键不在“能不能选”,而在“选完之后怎么改才不影响可维护性”。直接写 style 快,但容易散落、难追踪;靠 classList 干净,但要求提前写好对应 CSS;动态插规则灵活,却要小心跨浏览器兼容和注入时机。真正难的是根据场景选对那条路,而不是堆砌 API。