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

如何实现点击左右按钮切换月份名称的前端交互功能

月份切换功能实现方案

你要实现的这个功能通用名称为月份步进选择器,也常作为日期选择器的子组件使用,效果如下图:
月份切换效果图

以下是可直接复用的交互逻辑实现:

实现逻辑说明

  1. 提前定义好12个月份的英文缩写数组,用索引变量记录当前选中的月份位置
  2. 点击右按钮时索引自增,超过11(数组最大下标)时重置为0,实现正向循环
  3. 点击左按钮时索引自减,小于0时重置为11,实现反向循环
  4. 每次索引变更后,将对应月份的缩写更新到展示框即可

完整JS代码

将以下代码插入到你的HTML文件的<script>标签中即可生效:

// 12个月份缩写配置
const monthList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
// 当前选中月份的索引,初始为0对应Jan
let currentIndex = 0;
// 获取DOM节点
const monthInput = document.getElementById('month');
const leftBtn = document.querySelector('.left button');
const rightBtn = document.querySelector('.right button');

// 右按钮切换逻辑
rightBtn.addEventListener('click', () => {
  currentIndex = (currentIndex + 1) % 12;
  monthInput.value = monthList[currentIndex];
});

// 左按钮切换逻辑
leftBtn.addEventListener('click', () => {
  currentIndex = currentIndex === 0 ? 11 : currentIndex - 1;
  monthInput.value = monthList[currentIndex];
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:09:00