

新闻资讯
技术学院JavaScript通过style属性或classList控制DOM样式,推荐用CSS类切换;style需驼峰命名,getComputedStyle获取计算后样式,批量操作应避免强制同步布局。
JavaScript 通过操作 DOM 元素的 style 属性或 CSS 类名,就能直接控制元素的视觉表现。核心思路是:要么内联改单个样式,要么切换预定义的 CSS 类——后者更推荐,结构清晰、易于维护。
每个 DOM 元素都有一个 style 属性,它是一个只读的 CSSStyleDeclaration 对象,但可以赋值。注意:CSS 中的连字符写法(如 background-color)要转成驼峰命名(backgroundColor)。
const box = document.getElementById('myBox');
box.style.color = 'red';
Object.assign):Object.assign(box.style, {
width: '200px',
height: '100px',
background: '#3498db',
borderRadius: '8px'
});把样式逻辑写在 CSS 文件里,JS 只负责“开关”类名,这样样式和行为分离,可复用、易调试。
box.classList.add('active');
box.classList.remove('hidden');
box.classList.toggle('highlight');
if (box.classList.contains('disabled')) { ... }
box.className = 'btn
btn-primary btn-lg';(慎用,会覆盖所有现有类)如果想获取元素最终生效的样式(包括继承、浏览器默认、媒体查询匹配后的值),不能用 element.style.xxx(它只返回内联样式),而要用 window.getComputedStyle()。
const computed = getComputedStyle(box);console.log(computed.width); // 返回 '200px'console.log(computed.backgroundColor); // 'rgb(52, 152, 219)'频繁读写 style 或 offsetHeight 等会触发浏览器重排(reflow),影响性能。建议“读一批、写一批”,或用 requestAnimationFrame 批量处理。
for (let i = 0; i < items.length; i++) {
items[i].style.left = i * 10 + 'px';
console.log(items[i].offsetTop); // 强制同步计算const tops = items.map(el => el.offsetTop);
items.forEach((el, i) => el.style.left = tops[i] * 2 + 'px');