在JavaScript中实现日期年月选择的功能,通常会使用HTML的<input type="date">
元素或者第三方库如jQuery UI Datepicker、Flatpickr等。以下是使用原生HTML和JavaScript实现的一个简单示例:
以下是一个简单的原生HTML和JavaScript实现年月选择的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>年月选择器</title>
<style>
/* 简单的样式调整 */
input[type="date"] {
padding: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<label for="yearMonthPicker">选择年月:</label>
<input type="date" id="yearMonthPicker" name="yearMonthPicker" min="2000-01-01" max="2099-12-31" step="1M">
<script>
// 获取输入元素
const yearMonthPicker = document.getElementById('yearMonthPicker');
// 监听日期变化事件
yearMonthPicker.addEventListener('change', function() {
const selectedDate = new Date(this.value);
const year = selectedDate.getFullYear();
const month = selectedDate.getMonth() + 1; // 月份从0开始,所以加1
console.log(`选择的年月是: ${year}-${month}`);
});
</script>
</body>
</html>
<input type="date">
元素。通过上述方法,你可以实现一个简单且功能齐全的年月选择器,满足大多数应用场景的需求。
领取专属 10元无门槛券
手把手带您无忧上云