JavaScript DOM 样式操作
这一篇是 DOM 操作系列的收尾,讲样式。改样式有三种途径,用 .style 改行内样式,用 classList 切换类名,用 getComputedStyle 读取最终生效的样式。分别看什么时候用哪个。
用 .style 修改行内样式
每个元素都有 style 属性,改它就是在元素上写行内样式。注意属性名要用驼峰写法,CSS 里的连字符要去掉,后一个单词首字母大写,比如 background-color 对应 backgroundColor,font-size 对应 fontSize。
const box = document.querySelector('#box');
box.style.backgroundColor = 'red';
box.style.fontSize = '20px';
box.style.marginTop = '10px';
效果等同于在 HTML 里写 style=”background-color: red; font-size: 20px;”。属性名要对照 CSS 逐个转驼峰,写多了容易记混,但这是最直接的改样式方式。
看一个按钮点击改变颜色的例子。
<button id="btn">点我变红</button>
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
btn.style.backgroundColor = 'red';
});
点击后按钮背景变红。
用 classList 切换类
更推荐的思路是,样式定义在 CSS 里,JavaScript 只负责切换类名。样式逻辑归 CSS,交互逻辑归 JS,职责清晰。classList 的用法在 JavaScript 操作 DOM 内容与属性 里介绍过,这里看一个高亮开关。
.highlight {
background-color: yellow;
font-weight: bold;
}
<button id="btn">开关高亮</button>
<p id="text">这是一段文字</p>
const btn = document.querySelector('#btn');
const text = document.querySelector('#text');
btn.addEventListener('click', () => {
text.classList.toggle('highlight');
});
每点一次按钮,文字在普通和高亮两种状态之间切换,多个样式属性一次搞定,比用 .style 一个个改清爽得多。
用 getComputedStyle 读取最终样式
.style 只能读到行内样式,外部样式表里定义的样式用 .style 是读不到的。
#box {
background-color: green;
}
const box = document.querySelector('#box');
console.log(box.style.backgroundColor); // 空字符串,外部样式表里的值读不到
想读元素最终生效的样式,用 getComputedStyle,它返回一个只读的样式对象,外部样式表、行内样式、浏览器默认样式全部计算在内。
const box = document.querySelector('#box');
const style = getComputedStyle(box);
console.log(style.backgroundColor); // rgb(0, 128, 0),外部样式表里的 green 生效了
记住一点,getComputedStyle 只用来读,返回的对象不可修改,改样式还是用 .style 或 classList。
小结
- .style 修改行内样式,属性名用驼峰写法,backgroundColor 对应 background-color。
- 推荐用 classList 切换类名,样式写在 CSS 里,交互只负责加类和去类。
- getComputedStyle 读取元素最终生效的样式,只读,能拿到外部样式表里的值。
- 改样式用 .style 或 classList,读样式用 getComputedStyle。
- DOM 基础到这里就齐了,下一篇开始学事件,让页面真正动起来。