You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现多animated容器独立循环,每5秒切换highlighted类

实现多个animated容器独立循环切换高亮类

核心思路

给每个.animated容器单独绑定循环逻辑,每个容器维护自己的当前高亮索引,每隔5秒切换子元素的highlighted类,互不干扰。

实现代码

// 获取所有animated容器
const animatedContainers = document.querySelectorAll('.animated');

// 遍历每个容器,单独初始化循环逻辑
animatedContainers.forEach(container => {
  // 获取当前容器下的所有.boxed子元素
  const boxedItems = container.querySelectorAll('.boxed');
  let currentIndex = 0;

  // 初始化:给第一个元素添加highlighted类
  if (boxedItems.length > 0) {
    boxedItems[currentIndex].classList.add('highlighted');
  }

  // 启动当前容器的独立循环定时器
  setInterval(() => {
    // 移除上一个元素的高亮类
    boxedItems[currentIndex].classList.remove('highlighted');
    // 更新索引,循环到开头
    currentIndex = (currentIndex + 1) % boxedItems.length;
    // 给新元素添加高亮类
    boxedItems[currentIndex].classList.add('highlighted');
  }, 5000); // 5秒间隔
});

代码说明

  • 先通过querySelectorAll('.animated')获取所有目标容器,确保每个容器单独处理。
  • 对每个容器,单独获取其内部的.boxed子元素,维护自己的currentIndex变量,不会和其他容器混淆。
  • 每个容器启动独立的setInterval定时器,各自按5秒间隔切换高亮状态,所有容器同时运行且互不影响。
  • 用取余运算(currentIndex + 1) % boxedItems.length实现索引循环,避免越界。

注意事项

  • 确保每个.animated容器的子元素都是.boxed类,或者根据实际情况调整选择器。
  • 如果容器内没有子元素,代码会自动跳过,避免报错。

内容的提问来源于stack exchange,提问作者SwiftChild

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:27:35