← 返回目录

5. style / className / classList

改样式有三种方式:直接改 style、改 className、用 classList。

核心三种:
element.style.color——改单个内联样式
element.className——直接替换整个 class
classList.add/remove/toggle——增删切换 class

坑:style 只能改内联样式、CSS 里的 - 要写成驼峰(backgroundColor)、classList 比 className 方便

5.1 互动演示(给这个盒子换装)

我是 styleBox,点按钮换我
点按钮: 盒子换装, 下面同步代码与结论。

5.2 知识点逐条讲解

① style:只能改"穿在身上的",而且要驼峰

CSS 里用短横线分开的词,到了 JS 里要把短横线去掉、后一个词首字母大写(这叫驼峰)。比如背景色:

CSS 里写JS 里写 style.什么
background-colorstyle.backgroundColor
font-sizestyle.fontSize
border-radiusstyle.borderRadius
// 抓到要改的盒子
let box = document.getElementById('styleBox');

// 改背景色(驼峰!不能写 background-color)
box.style.backgroundColor = 'lightblue';

// 改字号(带单位要写成 '20px' 字符串)
box.style.fontSize = '20px';

如果你用 style 去读外部 CSS 里写的样式,会读不到。因为 style 只管"直接写在标签 style= 里的那点",读不到你写在 <style> 或外面 CSS 文件里的;日常想切样式,优先用下面的 classList。

② className:一赋值就全换掉(大坑)

因为 class 是 JS 的保留字,不能写 box.class,只能写 box.className。它是一整串字,你一写新的,原来整串都被顶掉。

// 假设盒子原本 class="box base"
// 现在身上穿的是这两件
box.className = 'box base';

// 整串替换成只穿 active
box.className = 'active';

// 现在只剩 active!box、base 全被换没了

如果你用 className 只想加一个类,却发现别的类都没了。因为 className 是"整串替换"不是"加一个";想加得自己拼字符串(容易多空格少空格),所以日常别用它加单个类。

③ classList:四个小开关,推荐

小开关干什么
add('类名')加一个类,重复加也不报错
remove('类名')摘掉某个类,没有也不报错
toggle('类名')有就摘、没有就加(点一下高亮最常用)
contains('类名')问一句"有这个类吗",回答 true/false
// 只加 hl,别的不动
box.classList.add('hl');

// 只摘 base
box.classList.remove('base');

// 再点:有→摘,没有→加
box.classList.toggle('hl');

// true / false
box.classList.contains('hl');

实战:用在哪 / 常见坑 / 怎么解决

① 用在哪:按钮高亮、弹窗显隐、开关灯、主题切换。

② 常见坑:用 className 加类把别的类覆盖没了;style 驼峰写错读不到。

③ 怎么解决:单个类用 classList.add/remove/toggle;改样式优先切类,属性名写驼峰。

一句话记住:style 改身上、要驼峰;className 一写就整串换;classList 的 add/remove/toggle/contains 只动一个类,日常首选它。

本页重点

API作用参数返回值代码示例
元素.style改行内样式(驼峰)属性名/值样式对象box.style.color = 'red';
元素.className整串 class,一写就覆盖字符串类名字符串box.className = 'active';
classList.add()加一个类,不动别的类名box.classList.add('active');
classList.toggle()有就摘没有就加类名box.classList.toggle('active');
classList.contains()问有没有这个类类名true/falseif (box.classList.contains('active')) fn();