如何实现点击左右按钮切换月份名称的前端交互功能
月份切换功能实现方案
你要实现的这个功能通用名称为月份步进选择器,也常作为日期选择器的子组件使用,效果如下图:
以下是可直接复用的交互逻辑实现:
实现逻辑说明
- 提前定义好12个月份的英文缩写数组,用索引变量记录当前选中的月份位置
- 点击右按钮时索引自增,超过11(数组最大下标)时重置为0,实现正向循环
- 点击左按钮时索引自减,小于0时重置为11,实现反向循环
- 每次索引变更后,将对应月份的缩写更新到展示框即可
完整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
相关产品推荐
相关产品推荐

