求助:使用HTML+Moment.js实现可切换周的日期列表功能
修正后的周日期切换代码
testing.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>周日期切换</title> <style> .date-container { display: flex; align-items: center; gap: 1rem; padding: 1rem; } .date-list { display: flex; gap: 0.5rem; list-style: none; padding: 0; margin: 0; } .date-item { padding: 0.5rem 1rem; border: 1px solid #ddd; border-radius: 4px; cursor: pointer; } .date-item.active { background-color: #007bff; color: white; border-color: #007bff; } button { padding: 0.5rem 1rem; cursor: pointer; } </style> </head> <body> <div class="date-container"> <button id="prevWeek"><</button> <ul id="dateList" class="date-list"></ul> <button id="nextWeek">></button> </div> <script src="datelist.js"></script> </body> </html>
datelist.js
// 固定初始起始日期:2021-10-22 let currentStartDate = new Date('2021-10-22'); // 页面加载后渲染初始周 renderWeekDates(); // 绑定上一周切换事件 document.getElementById('prevWeek').addEventListener('click', () => { currentStartDate.setDate(currentStartDate.getDate() - 7); renderWeekDates(); }); // 绑定下一周切换事件 document.getElementById('nextWeek').addEventListener('click', () => { currentStartDate.setDate(currentStartDate.getDate() + 7); renderWeekDates(); }); // 渲染当前周的7个日期 function renderWeekDates() { const dateListEl = document.getElementById('dateList'); dateListEl.innerHTML = ''; // 生成当前周连续7天的日期 for (let i = 0; i < 7; i++) { const targetDate = new Date(currentStartDate); targetDate.setDate(currentStartDate.getDate() + i); // 格式化日期为YYYY-MM-DD格式 const formattedDate = `${targetDate.getFullYear()}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`; const dateItem = document.createElement('li'); dateItem.className = 'date-item'; dateItem.textContent = formattedDate; // 标记初始指定的日期为高亮状态 if (formattedDate === '2021-10-22') { dateItem.classList.add('active'); } dateListEl.appendChild(dateItem); } }
关键修正说明
- 固定初始日期:将起始日期硬编码为
2021-10-22,彻底替换掉原代码中使用当前系统日期的逻辑 - 简化切换逻辑:切换周直接对起始日期进行±7天计算,保证每周7天的连续性,逻辑清晰无混乱
- 独立渲染函数:将日期列表的生成和渲染封装为独立函数,每次切换后重新渲染,避免DOM操作逻辑混杂
- 高亮初始日期:给指定的
2021-10-22添加高亮样式,方便识别初始日期位置
如果需要按自然周(如周一至周日)计算,只需调整currentStartDate为对应周的起始日即可。例如要以2021-10-22所在自然周(周一10-18至周日10-24)为初始周,将初始日期改为new Date('2021-10-18')即可。
内容的提问来源于stack exchange,提问作者SNAZ
相关产品推荐
相关产品推荐

