原生 JavaScript 如何为容器元素循环添加三类 CSS 类

作者:袖梨 2026-07-15

本文教你用纯 javascript(无需 jquery)为一组具有相同初始类名的容器元素,按 1→2→3→1→2→3 的规律循环添加不同的 css 类,实现样式轮换效果。

本文教你用纯 javascript(无需 jquery)为一组具有相同初始类名的容器元素,按 1→2→3→1→2→3 的规律循环添加不同的 css 类,实现样式轮换效果。

要实现容器元素的类名循环分配(如 test1 → test2 → test3 → test1 …),核心思路是:获取所有目标元素,遍历并根据索引位置计算余数,动态添加对应类名。以下是推荐的、简洁可靠的实现方案:

✅ 推荐写法(推荐初学者使用)

// 获取所有 class="test" 的 div 元素const containers = document.querySelectorAll('.test');// 遍历每个元素,按索引 % 3 + 1 计算循环编号(1, 2, 3)containers.forEach((el, index) => {  const cycleIndex = (index % 3) + 1; // 得到 1、2、3、1、2、3...  el.className = `test${cycleIndex}`; // 直接替换整个 class 属性(注意:会移除原始 "test")});

⚠️ 注意:el.className = ... 会完全覆盖原有类名(包括初始的 test)。若需保留原始类或叠加类名,应使用 classList:

✅ 更灵活的写法(保留原始类并叠加新类)

const containers = document.querySelectorAll('.test');containers.forEach((el, index) => {  const cycleIndex = (index % 3) + 1;  // 先清除可能已存在的 test1/test2/test3 类  el.classList.remove('test1', 'test2', 'test3');  // 再添加对应的新类  el.classList.add(`test${cycleIndex}`);});

这样既保持了语义清晰,又避免了类名冲突,且兼容性良好(支持所有现代浏览器及 IE10+)。

? 关键知识点说明:

  • document.querySelectorAll('.test') 返回静态 NodeList,安全可靠;
  • index % 3 是实现循环的核心:索引 0,1,2,3,4,5... 对应余数 0,1,2,0,1,2...,加 1 后即得 1,2,3,1,2,3...;
  • classList.add() 和 .remove() 是操作类名的标准、安全方式,优于直接拼接字符串;
  • 不建议使用全局计数器(如 count++)——易出错且不必要,索引天然提供唯一序号。

? 补充:CSS 类定义建议(与 HTML 一致)

确保你的 CSS 正确声明了样式:

立即学习“Java免费学习笔记(深入)”;

.test1 { background: blue; }.test2 { background: green; }.test3 { background: yellow; }/* .test 原始类可留作基础样式或删除(因已被替换) */

运行上述脚本后,HTML 将自动变为:

<div class="test test1">This container must have class="test1"</div><div class="test test2">This container must have class="test2"</div><div class="test test3">This container must have class="test3"</div><div class="test test1">From here the function need repeat so this container must have class="test1"</div><!-- 依此类推 -->

✅ 总结:只需 4 行核心代码,即可实现任意数量容器的三阶循环样式分配——简洁、可读、无依赖、适合初学者理解与复用。

相关文章

精彩推荐