使用JavaScript实现下拉选择今日、本周、本月、本年来控制给时间选择框赋值对应时间的方法
1.首先,你需要在HTML中创建一个下拉选择框,并为其添加一个事件监听器,以便在选择项发生变化时触发相应的函数。
// An highlighted block
<select id="timeSelect" onchange="updateTime()">
<option value="today">今日</option>
<option value="thisWeek">本周</option>
<option value="thisMonth">本月</option>
<option value="thisYear">本年</option>
</select>;
2.接下来,在JavaScript中编写一个函数来根据选择的项更新时间选择框的值。你可以使用Date对象和相关方法来获取当前日期和时间,并根据选择的项计算出对应的时间范围。
// An highlighted block
function updateTime() {
var select = document.getElementById("timeSelect");
var selectedValue = select.value;
var startDate, endDate;
var today = new Date();
var currentYear = today.getFullYear();
var currentMonth = today.getMonth();
var currentDay = today.getDate();
if (selectedValue === "today") {
startDate = new Date(currentYear, currentMonth, currentDay);
endDate = new Date(currentYear, currentMonth, currentDay);
} else if (selectedValue === "thisWeek") {
var firstDayOfWeek = currentDay - today.getDay();
startDate = new Date(currentYear, currentMonth, firstDayOfWeek);
endDate = new Date(currentYear, currentMonth, firstDayOfWeek + 6);
} else if (selectedValue === "thisMonth") {
startDate = new Date(currentYear, currentMonth, 1);
endDate = new Date(currentYear, currentMonth + 1, 0);
} else if (selectedValue === "thisYear") {
startDate = new Date(currentYear, 0, 1);
endDate = new Date(currentYear, 11, 31);
}
// 将日期格式化为字符串并赋值给时间选择框
var startDateString = startDate.toISOString().split("T")[0]; var endDateString = endDate.toISOString().split("T")[0];
document.getElementById("startDate").value = startDateString;
document.getElementById("endDate").value = endDateString;
}
3.最后,在HTML中添加两个文本输入框,用于显示选择的时间范围。
// An highlighted block
<input type="text" id="startDate" readonly>
<input type="text" id="endDate" readonly>