JavaScript实现点击MOVE按钮后12个盒子间隔1秒依次点亮
实现12个盒子依次自动点亮的JavaScript方案
问题分析
你现有的代码仅针对单个盒子s1做状态切换,且start函数中调用的toggle未定义,无法实现12个盒子依次点亮的需求。以下是修改后的完整实现方案:
完整代码实现
// 盒子总数(对应id为s1到s12) const totalBoxes = 12; // 当前待点亮的盒子索引(从1开始) let currentBoxIndex = 1; let timerId = null; // 点亮指定索引的盒子 const lightBox = (index) => { const box = document.getElementById(`s${index}`); // 若需保持点亮状态,直接添加on类;若需切换则用toggle box.classList.add('on'); }; // 停止自动点亮并重置状态 const stopAutoLight = () => { clearTimeout(timerId); currentBoxIndex = 1; }; // 启动依次点亮流程 const startAutoLight = () => { // 先清除已有定时器,避免重复触发 stopAutoLight(); // 递归处理下一个盒子 const processNextBox = () => { if (currentBoxIndex > totalBoxes) { // 所有盒子点亮完毕,停止流程 stopAutoLight(); return; } lightBox(currentBoxIndex); currentBoxIndex++; timerId = setTimeout(processNextBox, 1000); }; // 立即点亮第一个盒子,再启动后续定时 lightBox(currentBoxIndex); currentBoxIndex++; timerId = setTimeout(processNextBox, 1000); }; // 绑定MOVE按钮点击事件 document.querySelector('#moveBtn').addEventListener('click', startAutoLight);
关键说明
- 状态重置:每次点击MOVE按钮时先调用
stopAutoLight,清除之前的定时器并重置索引,避免多次点击导致混乱 - 递归定时:通过
processNextBox递归函数,每隔1秒点亮下一个盒子,直到12个盒子全部处理完毕 - 灵活调整:如果需要循环点亮(全部亮完后重新开始),可将
processNextBox中的停止逻辑改为重置currentBoxIndex = 1后继续调用processNextBox
内容的提问来源于stack exchange,提问作者Jaymie Redman
相关产品推荐
相关产品推荐

