本文介绍如何使用纯 JavaScript(不依赖 jQuery)为一组具有相同初始类名的容器元素,按 1-2-3 顺序循环添加 test1/test2/test3 类,实现背景色等样式的周期性切换。
本文介绍如何使用纯 javascript(不依赖 jquery)为一组具有相同初始类名的容器元素,按 1-2-3 顺序循环添加 `test1`/`test2`/`test3` 类,实现背景色等样式的周期性切换。
要实现 HTML 容器元素按固定周期(如每 3 个一组)循环应用不同 CSS 类(例如 test1、test2、test3),核心思路是:获取所有目标元素 → 遍历并根据索引计算余数 → 动态添加对应类名。以下为完整、可直接运行的解决方案。
// 获取所有 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()(见下文进阶建议)。
<!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>
element.classList.remove('test', 'test1', 'test2', 'test3');element.classList.add(`test${(index % 3) + 1}`);
for (let i = 0; i < containers.length; i++) { containers[i].className = `test${(i % 3) + 1}`;}
document.addEventListener('DOMContentLoaded', () => { // 上述代码放在这里});
掌握这一模式后,你可轻松扩展为任意循环数(如 % 4 实现四类轮换),或结合数据驱动动态生成类名,为前端样式控制打下坚实基础。