JS实现日期滚动选择
实现日期滚动选择的基本思路
使用HTML、CSS和JavaScript创建一个日期滚动选择器,允许用户通过滚动选择年、月、日。核心是通过监听滚动事件,动态更新显示的值。
HTML结构
创建一个包含年、月、日三个独立滚动区域的容器。每个区域使用<div>包裹,内部通过<ul>列表展示可选值。

<div class="date-picker">
<div class="scroll-area" id="year">
<ul></ul>
</div>
<div class="scroll-area" id="month">
<ul></ul>
</div>
<div class="scroll-area" id="day">
<ul></ul>
</div>
</div>
CSS样式
设置滚动区域的样式,确保内容垂直排列且可滚动。通过CSS隐藏滚动条并居中显示当前选中项。
.date-picker {
display: flex;
width: 100%;
height: 200px;
overflow: hidden;
}
.scroll-area {
flex: 1;
height: 100%;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.scroll-area ul {
padding: 0;
margin: 0;
list-style: none;
}
.scroll-area li {
height: 40px;
display: flex;
align-items: center;
justify-content: center;
scroll-snap-align: center;
}
JavaScript逻辑
动态生成年、月、日的可选值,并绑定滚动事件。通过计算滚动位置确定当前选中的值。

// 初始化数据
const currentYear = new Date().getFullYear();
const years = Array.from({ length: 100 }, (_, i) => currentYear - 50 + i);
const months = Array.from({ length: 12 }, (_, i) => i + 1);
const days = Array.from({ length: 31 }, (_, i) => i + 1);
// 填充列表
function populateList(elementId, items) {
const ul = document.querySelector(`#${elementId} ul`);
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
ul.appendChild(li);
});
}
populateList('year', years);
populateList('month', months);
populateList('day', days);
// 监听滚动事件
document.querySelectorAll('.scroll-area').forEach(area => {
area.addEventListener('scroll', function() {
const liHeight = 40;
const scrollTop = this.scrollTop;
const selectedIndex = Math.round(scrollTop / liHeight);
const selectedValue = this.querySelectorAll('li')[selectedIndex].textContent;
console.log(`${this.id}: ${selectedValue}`);
});
});
优化选中项居中
使用CSS的scroll-snap特性确保滚动停止时选中项自动居中。修改.scroll-area的CSS:
.scroll-area {
scroll-snap-type: y mandatory;
}
.scroll-area li {
scroll-snap-align: center;
}
动态更新天数
根据选择的年份和月份动态更新天数,处理不同月份的天数差异(如闰年二月)。
function updateDays(year, month) {
const daysInMonth = new Date(year, month, 0).getDate();
const dayList = document.querySelector('#day ul');
dayList.innerHTML = '';
const days = Array.from({ length: daysInMonth }, (_, i) => i + 1);
populateList('day', days);
}
document.querySelector('#year').addEventListener('scroll', function() {
const year = getSelectedValue('year');
const month = getSelectedValue('month');
updateDays(year, month);
});
document.querySelector('#month').addEventListener('scroll', function() {
const year = getSelectedValue('year');
const month = getSelectedValue('month');
updateDays(year, month);
});
function getSelectedValue(elementId) {
const area = document.querySelector(`#${elementId}`);
const liHeight = 40;
const scrollTop = area.scrollTop;
const selectedIndex = Math.round(scrollTop / liHeight);
return area.querySelectorAll('li')[selectedIndex].textContent;
}
完整代码示例
整合上述代码,实现一个完整的日期滚动选择器。用户可以通过滚动选择年、月、日,且天数会根据年月动态调整。






