JavaScript: DOM 样式
会用 JS 改页面的内容和结构后,下一步就是控制样式——让元素变色、显隐、换皮肤。CSS 负责静态样式,JS 负责动态样式,两者配合才能做交互。
1. style 属性
element.style 对应 HTML 的内联样式(style="...")。它只能读写内联样式,读不到 CSS 文件或 <style> 标签里定义的规则。
HTML
<div id="box">Hello Style</div>
<script>
const element = document.getElementById('box');
element.style.color = 'red';
element.style.fontSize = '20px'; // 注意:CSS 的 font-size → JS 的 fontSize
</script>
⚠️ 注意: CSS 属性名中有连字符的,在 JS 中要转成驼峰:
background-color → backgroundColor、font-size → fontSize。这是初学者最容易踩的坑之一。
▶ 示例
JAVASCRIPT
// 本节代码示例
const message = "你好,世界!";
console.log(message);
这是最简单的示例,后续章节会详细解释。### ▶ 示例:style 属性读写
HTML
<div id="box" style="color: blue;">Hello Style</div>
<script>
const box = document.getElementById('box');
console.log('当前颜色:', box.style.color);
box.style.color = 'red';
box.style.fontSize = '24px';
box.style.backgroundColor = '#f0f0f0';
box.style.padding = '10px';
box.style.borderRadius = '8px';
</script>
2. className 与 classList
操作元素的 class 是 JS 改样式最常用的方式——你提前在 CSS 中写好类,JS 只需添加或移除类名即可。
(1) className
className 是一个字符串,赋值会覆盖所有已有的类。
HTML
<div id="demo1" class="item">元素1</div>
<div id="demo2" class="item">元素2</div>
<script>
const el1 = document.getElementById('demo1');
el1.className = 'active'; // 覆盖,只剩 active
const el2 = document.getElementById('demo2');
el2.className += ' highlight'; // 追加,但原始且易出错
console.log('el1.className:', el1.className);
console.log('el2.className:', el2.className);
</script>
💡 提示: 用
className 赋值就像给手机恢复出厂设置再装新 App——之前的全没了。大多数场景用 classList 更安全。
(2) classList
classList 是一个 DOMTokenList 对象,提供了增删改查类的方法,不会误伤其他类。
| 方法 | 说明 |
|---|---|
add('cls') |
添加类 |
remove('cls') |
移除类 |
toggle('cls') |
有则移除,无则添加 |
contains('cls') |
是否包含,返回布尔值 |
▶ 示例:主题切换
HTML
<style>
.dark { background: #222; color: #fff; }
.light { background: #fff; color: #222; }
body { transition: background 0.3s, color 0.3s; padding: 20px; }
</style>
<body class="light">
<h2>主题切换演示</h2>
<p>点击按钮在明暗主题间切换</p>
<button id="toggleBtn">切换主题</button>
</body>
<script>
const body = document.body;
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', function() {
body.classList.toggle('dark');
body.classList.toggle('light');
});
</script>
▶ 示例:显示与隐藏
HTML
<style>
.hidden { display: none; }
.panel { border: 1px solid #ccc; padding: 15px; margin-top: 10px; }
</style>
<button id="togglePanel">显示/隐藏面板</button>
<div id="panel" class="panel">这是面板内容</div>
<script>
const panel = document.getElementById('panel');
const btn = document.getElementById('togglePanel');
btn.addEventListener('click', function() {
panel.classList.toggle('hidden');
btn.textContent = panel.classList.contains('hidden') ? '显示面板' : '隐藏面板';
});
</script>
3. getComputedStyle
element.style 只能读内联样式,那 CSS 文件或 <style> 标签里定义的样式怎么读?答案是 getComputedStyle。
HTML
<div id="box">测试元素</div>
<script>
const element = document.getElementById('box');
const style = window.getComputedStyle(element);
console.log(style.color); // "rgb(0, 0, 0)"
console.log(style.fontSize); // "16px"
</script>
💡 提示:
getComputedStyle 返回的是元素最终的计算样式——浏览器把所有 CSS 来源(内联、style 标签、CSS 文件、继承)合并后的结果。返回值是只读的。
▶ 示例:获取计算样式
HTML
<style>
#measured { font-size: 18px; color: green; margin: 20px; }
</style>
<div id="measured">测测我的样式</div>
<script>
const el = document.getElementById('measured');
console.log('style属性读到的color:', el.style.color);
console.log('计算样式读到的color:', getComputedStyle(el).color);
console.log('计算样式读到的fontSize:', getComputedStyle(el).fontSize);
console.log('计算样式读到的margin:', getComputedStyle(el).margin);
</script>
4. cssText 批量设置
如果一个元素要同时设置多个内联样式,逐行写 style.xxx = ... 太啰嗦。cssText 可以一次性写完。
HTML
<div id="box">批量设置样式</div>
<script>
const element = document.getElementById('box');
element.style.cssText = 'color: red; font-size: 20px; padding: 10px;';
</script>
⚠️ 注意:
cssText 赋值会替换所有已有的内联样式。如果想追加,用 +=:element.style.cssText += '; color: red;'。
▶ 示例:cssText 批量设置
HTML
<div id="box">批量设置样式</div>
<script>
const box = document.getElementById('box');
box.style.cssText = 'color: white; background: #4CAF50; padding: 15px; border-radius: 8px; font-size: 18px; text-align: center;';
</script>
❓ 常见问题
Q 为什么
element.style.color 读不到 CSS 文件里设的颜色?A
style 属性只对应内联 style="...",CSS 文件和 <style> 标签里的规则不在它的管辖范围。用 getComputedStyle(element).color 才能读到最终值。Q
classList.toggle 能否根据条件决定添加还是移除?A 可以。
classList.toggle('cls', force) 传入第二个参数:true 强制添加,false 强制移除。等价于 force ? add : remove。Q 修改样式用
style 还是用 classList 好?A 规则很简单:改一两个临时样式用
style,切换状态/主题用 classList + CSS 类。后者把样式留给 CSS,逻辑留给 JS,维护更轻松。📖 小节
element.style只操作内联样式,读不到 CSS 文件中的规则;写时属性名要用驼峰className赋值会覆盖所有类,用classList的add/remove/toggle更安全getComputedStyle读取元素最终计算样式,返回值只读cssText批量设置内联样式,但赋值会替换已有内联样式
📝 作业
- 基础:创建一个页面,有 3 个按钮(红/绿/蓝),点击后用
style.backgroundColor改变页面背景色。 - 进阶:用
classList.toggle实现一个"高亮"功能——点击段落切换高亮类(背景变黄),再点击取消。 - 挑战:实现一个简易"夜间模式"——点击按钮切换,用
getComputedStyle读取当前背景色判断模式,并在页面上显示"当前模式:日间/夜间"。