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

如何使用JavaScript实现基于数组的背景颜色切换功能

基于数组的背景颜色切换功能实现(JavaScript)

功能说明

通过点击「上一个颜色」和「下一个颜色」按钮,切换指定容器的背景颜色,颜色选项预先存储在数组中。


HTML 结构示例

<!-- 颜色切换按钮 -->
<button id="prev">上一个颜色</button>
<button id="next">下一个颜色</button>

<!-- 需要切换背景的目标容器 -->
<div class="back-color">
  这里是要切换背景颜色的内容区域
</div>

JavaScript 实现代码

// 定义背景颜色数组
let back_color = ['#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2'];
let currentIndex = 0;

// 绑定「上一个颜色」按钮点击事件
$("#prev").click(function () {
    // 索引切换逻辑:当前为第一个时跳转到最后一个,否则向前一位
    currentIndex = currentIndex > 0 ? --currentIndex : back_color.length - 1;
    $('.back-color').css("background", back_color[currentIndex]);
});

// 绑定「下一个颜色」按钮点击事件
$("#next").click(function () {
    // 索引切换逻辑:当前为最后一个时跳转到第一个,否则向后一位
    currentIndex = currentIndex < back_color.length - 1 ? ++currentIndex : 0;
    $('.back-color').css("background", back_color[currentIndex]);
});

注意事项

原代码的索引判断存在逻辑漏洞(如点击上一个按钮时,初始索引0会变为-1,导致无法正确获取颜色值),上述代码已修正该问题,确保索引始终在数组有效范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:45:37