如何使用JavaScript实现流行色展示页的increase增加按钮功能
年度流行色切换功能实现方案
你现有代码存在两个核心问题:
- 定义
bgText颜色列表时直接执行了DOM赋值操作,数组初始化完成后页面会直接被覆盖为最后一组2020年的颜色数据,且数组内存储的是赋值结果而非原始配置数据 - 缺少当前展示数据的索引标记,无法记录当前切换到了第几个年份的颜色
完整修改后的代码
// 颜色列表选择器变量 const year = document.querySelector("#copy .year"); const bgColor = document.querySelector("#color_bg"); const bgInnerTitle = document.querySelector("#color_bg h1"); const bgInnerText = document.querySelector("#color_bg p"); const increase = document.querySelector("#btn .increase"); const decrease = document.querySelector("#btn .decrease"); // 仅存储纯数据,不要在定义时执行DOM操作 const bgText = [ { year : "2017", color: "Greenery", number: "15-0343", bg: "#84bd00" }, { year : "2018", color: "Ultra Violet", number: "18-3838", bg: "#5f4b8b" }, { year : "2019", color: "Living Coral", number: "16-1546", bg: "#FF6D70" }, { year : "2020", color: "Classic Blue", number: "19-4052", bg: "#004680" } ]; // 定义当前展示的索引,默认0对应2017,要默认展示2020就设为3 let currentIndex = 0; // 封装公共渲染函数,传入索引就更新页面内容 function renderColor(index) { const currentData = bgText[index]; year.innerText = currentData.year; bgInnerTitle.innerText = currentData.color; bgInnerText.innerText = currentData.number; bgColor.style.backgroundColor = currentData.bg; } // 初始化渲染默认值 renderColor(currentIndex); // 减少按钮逻辑 decrease.addEventListener("click", function decreaseYear(){ // 边界判断:到第一个之后切到最后一个,不需要循环就替换为下方注释的写法 currentIndex = currentIndex - 1 < 0 ? bgText.length - 1 : currentIndex - 1; // 不需要循环的写法:currentIndex = Math.max(currentIndex - 1, 0) renderColor(currentIndex); }); // 增加按钮逻辑 increase.addEventListener("click", function increaseYear(){ // 边界判断:到最后一个之后切到第一个,不需要循环就替换为下方注释的写法 currentIndex = currentIndex + 1 >= bgText.length ? 0 : currentIndex + 1; // 不需要循环的写法:currentIndex = Math.min(currentIndex + 1, bgText.length - 1) renderColor(currentIndex); });
逻辑说明
- 先把颜色配置改为纯数据结构,避免定义数组时直接修改页面内容
- 新增
currentIndex变量记录当前展示的颜色在数组中的位置 - 封装公共渲染函数,所有切换操作都调用这个函数更新页面,避免重复代码
- 按钮点击时先修改索引值,做边界判断避免数组越界,再调用渲染函数更新页面内容
内容的提问来源于stack exchange,提问作者moolbum
相关产品推荐
相关产品推荐

