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

作者:袖梨 2026-07-15

本文介绍如何使用纯 JavaScript(不依赖 jQuery)为一组具有相同初始类名的容器元素,按 1-2-3 顺序循环添加 test1/test2/test3 类,实现背景色等样式的周期性切换。

本文介绍如何使用纯 javascript(不依赖 jquery)为一组具有相同初始类名的容器元素,按 1-2-3 顺序循环添加 `test1`/`test2`/`test3` 类,实现背景色等样式的周期性切换。

要实现 HTML 容器元素按固定周期(如每 3 个一组)循环应用不同 CSS 类(例如 test1、test2、test3),核心思路是:获取所有目标元素 → 遍历并根据索引计算余数 → 动态添加对应类名。以下为完整、可直接运行的解决方案。

✅ 推荐写法:使用 forEach + 模运算(简洁可靠)

// 获取所有 class="test" 的元素const containers = document.querySelectorAll('.test');containers.forEach((element, index) => {  // 计算循环序号:0→1, 1→2, 2→3, 3→1, 4→2, 5→3...  const cycleIndex = (index % 3) + 1;  // 移除原始 class="test"(可选,避免样式冲突),再添加新类  element.className = `test${cycleIndex}`;});

? 说明:index % 3 得到 0、1、2,加 1 后变为 1、2、3,完美匹配需求。使用 element.className = ... 可彻底替换原有类;若需保留其他类,改用 element.className = 'other-class test' + cycleIndex 或更安全的 classList.replace()(见下文进阶建议)。

? HTML 与 CSS 示例(完整可测试)

<!DOCTYPE html><html><head><style>.test { background: red; color: white; padding: 10px; margin: 5px 0; }.test1 { background: blue; }.test2 { background: green; }.test3 { background: yellow; }</style></head><body><div class="test">This container must have class="test1"</div><div class="test">This container must have class="test2"</div><div class="test">This container must have class="test3"</div><div class="test">From here the function need repeat so this container must have class="test1"</div><div class="test">This container must have class="test2"</div><div class="test">This container must have class="test3"</div><script>  const containers = document.querySelectorAll('.test');  containers.forEach((el, i) => {    el.className = `test${(i % 3) + 1}`;  });</script></body></html>

⚠️ 注意事项与进阶建议

  • 避免重复添加类:若容器已含 test1 等类,直接 classList.add() 可能导致重复(如 test test1 test1)。推荐使用 className = ... 替换,或更精准地操作:
    element.classList.remove('test', 'test1', 'test2', 'test3');element.classList.add(`test${(index % 3) + 1}`);
  • 兼容性:querySelectorAll 和 forEach 在现代浏览器中完全支持(IE9+ 支持 querySelectorAll,但 IE 不支持 NodeList 的 forEach;如需兼容 IE,可用传统 for 循环):
    for (let i = 0; i < containers.length; i++) {  containers[i].className = `test${(i % 3) + 1}`;}
  • 执行时机:确保脚本在 DOM 加载完成后运行。可将 <script> 放在 </body> 前,或使用:
    document.addEventListener('DOMContentLoaded', () => {  // 上述代码放在这里});

掌握这一模式后,你可轻松扩展为任意循环数(如 % 4 实现四类轮换),或结合数据驱动动态生成类名,为前端样式控制打下坚实基础。

相关文章

精彩推荐