我有一个用户预订航班的日历。当用户点击日期时,日期被选择并显示在出发日期 Div 中,而在出发日期之后选择返回日期则显示在返回日期 Div 中,这看起来很正常,如图所示 .
当用户点击出发日期(例如 7 月 30 日)和返回日期 7 月 25 日时,就会出现问题。在这种情况下,返回日期显示为 7 月 27 日,出发日期显示为 7 月 30 日。
代码和 HTML 文件较大,因此这里是 fiddle 代码,以便更好地理解。我希望如果发生这种情况,日期应该切换,即较早的日期应该是出发日期,之后的日期应该是返回日期。
`<script>
// DOM elements
const calendarContainer = document.getElementById("calendar-container");
const clearDatesBtn = document.getElementById("clear-dates-btn");
const inboundDate = document.getElementById("inboundDate");
const outboundDate = document.getElementById("outboundDate");
const confirmDateBtn = document.getElementById("confirm-dates-btn");
const calenderClose = document.getElementById("calender__close");
// Event listener for Clear Dates button
clearDatesBtn.addEventListener("click", clearDates);
// Variables to store selected departure and return dates
let departureDate = null;
let returnDate = null;
// Function to create a calendar for a given month and year
function createCalendar(month, year) {
// Get the first day of the month
const date = new Date(year, month, 1);
// Get the number of days in the month
const daysInMonth = new Date(year, month + 1, 0).getDate();
// Create a div to hold the calendar
const calendarDiv = document.createElement("div");
calendarDiv.classList.add("zt-monthcalendar-section");
// Create a div to display the month name
const monthNameDiv = document.createElement("div");
monthNameDiv.classList.add("zt-calendar-monthname");
monthNameDiv.textContent = new Date(year, month).toLocaleString('default', { month: 'long', year: 'numeric' });
calendarDiv.appendChild(monthNameDiv);
// Create a div to hold the date boxes for the month
const calenderDateSection = document.createElement("div");
calenderDateSection.classList.add("zt-calenderdate-section");
// Get the current date to determine whether past dates should be disabled
const currentDate = new Date();
for (let day = 0; day < date.getDay(); day++) {
// Create empty date boxes for days before the start of the month
const dateboxDiv = createEmptyDateBox();
calenderDateSection.appendChild(dateboxDiv);
}
// Create date boxes for each day of the month
for (let day = 1; day <= daysInMonth; day++) {
const dateboxDiv = createDateBox(day, month, year);
// Disable past dates
if (year === currentDate.getFullYear() && month === currentDate.getMonth() && day < currentDate.getDate()) {
dateboxDiv.classList.add("disabled");
}
calenderDateSection.appendChild(dateboxDiv);
}
// Add the date boxes to the calendar div
calendarDiv.appendChild(calenderDateSection);
calendarContainer.appendChild(calendarDiv);
}
// Function to create an empty date box
function createEmptyDateBox() {
const dateboxDiv = document.createElement("div");
dateboxDiv.classList.add("zt-datebox-section");
return dateboxDiv;
}
// Function to create a date box for a specific day
function createDateBox(day, month, year) {
const dateboxDiv = document.createElement("div");
dateboxDiv.classList.add("zt-datebox-section");
const dateNumberSpan = document.createElement("span");
dateNumberSpan.textContent = day;
dateboxDiv.appendChild(dateNumberSpan);
// Add a click event listener to handle date selection
dateboxDiv.addEventListener("click", function (event) {
handleDateClick(event, dateboxDiv, day, month, year);
});
return dateboxDiv;
}
// Function to handle date selection
function handleDateClick(event, dateboxDiv, day, month, year) {
const currentDate = new Date();
// Check if the selected date is after the current date
if (year > currentDate.getFullYear() || (year === currentDate.getFullYear() && month >= currentDate.getMonth())) {
if (departureDate === dateboxDiv) {
// If the selected date is the same as the departure date, toggle same date selection
resetSameDates();
departureDate.classList.remove("is--depart", "cwhite");
departureDate = null;
dateboxDiv.classList.remove("is--depart", "cwhite");
dateboxDiv.classList.add("is--samedate");
updateSelectDateText("select_dep_date", formatDate(day, month, year));
updateSelectDateText("select_ret_date", formatDate(day, month, year));
document.getElementById("dep_content").classList.remove("date--active");
document.getElementById("ret_content").classList.add("date--active");
document.getElementById("cal_heading").textContent = "When are you returning?";
} else if (returnDate === dateboxDiv) {
// If the selected date is the same as the return date, reset the selection
resetSameDates();
departureDate = dateboxDiv;
dateboxDiv.classList.add("is--depart", "cwhite");
updateSelectDateText("select_dep_date", formatDate(day, month, year));
updateSelectDateText("select_ret_date", "Date");
document.getElementById("dep_content").classList.add("date--active");
document.getElementById("ret_content").classList.remove("date--active");
document.getElementById("cal_heading").textContent = "When are you departing?";
} else if (!departureDate) {
// If there is no departure date selected, set the selected date as the departure date
resetSameDates();
departureDate = dateboxDiv;
dateboxDiv.classList.add("is--depart", "cwhite");
updateSelectDateText("select_dep_date", formatDate(day, month, year));
updateSelectDateText("select_ret_date", "Date");
document.getElementById("dep_content").classList.add("date--active");
document.getElementById("ret_content").classList.remove("date--active");
document.getElementById("cal_heading").textContent = "When are you departing?";
} else if (!returnDate) {
console.log( '!return date is if');
returnDate = dateboxDiv;
updateSelectDateText("select_ret_date", formatDate(day, month, year));
dateboxDiv.classList.add("is--return");
highlightSelectedDates();
document.getElementById("ret_content").classList.add("date--active");
document.getElementById("dep_content").classList.remove("date--active");
document.getElementById("cal_heading").textContent = "When are you returning?";
updateClearDatesButton();
} else {
// If both departure and return dates are already selected, reset the selection
if (departureDate !== returnDate) {
returnDate.classList.remove("is--return");
}
resetSelectedDates();
departureDate = dateboxDiv;
dateboxDiv.classList.add("is--depart", "cwhite");
updateSelectDateText("select_dep_date", formatDate(day, month, year));
updateSelectDateText("select_ret_date", "Select Date");
document.getElementById("dep_content").classList.add("date--active");
document.getElementById("ret_content").classList.remove("date--active");
document.getElementById("cal_heading").textContent = "When are you departing?";
}
// Check if the return date is before the departure date
if (departureDate && returnDate) {
const depTimestamp = new Date(
parseInt(departureDate.dataset.year),
parseInt(departureDate.dataset.month),
parseInt(departureDate.textContent)
).getTime();
const retTimestamp = new Date(
parseInt(returnDate.dataset.year),
parseInt(returnDate.dataset.month),
parseInt(returnDate.textContent)
).getTime();
if (retTimestamp < depTimestamp) {
[departureDate, returnDate] = [returnDate, departureDate];
console.log('I am hee=re');
highlightSelectedDates();
}
}
}
}
// Function to reset selected dates
function resetSelectedDates() {
const dateboxes = document.querySelectorAll(".zt-datebox-section");
for (const datebox of dateboxes) {
datebox.classList.remove("is--depart", "is--return", "is--selected", "cwhite", "is--samedate");
}
departureDate = null;
returnDate = null;
}
// Function to reset same dates selection
function resetSameDates() {
const dateboxes = document.querySelectorAll(".zt-datebox-section");
for (const datebox of dateboxes) {
datebox.classList.remove("is--depart", "is--return", "is--selected", "cwhite", "is--samedate");
}
}
// Function to highlight selected dates on the calendar
function highlightSelectedDates() {
const dateboxes = document.querySelectorAll(".zt-datebox-section");
let start = parseInt(departureDate.textContent);
let end = parseInt(returnDate.textContent);
// Swap start and end dates if necessary
if (start > end) {
[start, end] = [end, start];
}
let isSelectedRange = false;
let isBetweenSelectedDates = false;
for (const datebox of dateboxes) {
if (isSelectedRange) {
datebox.classList.remove("is--selected");
}
if (isBetweenSelectedDates) {
datebox.classList.add("is--selected");
}
if (datebox === departureDate || datebox === returnDate) {
if (!isSelectedRange) {
isSelectedRange = !isSelectedRange;
} else {
isSelectedRange = false;
isBetweenSelectedDates = false;
}
}
if (isSelectedRange) {
isBetweenSelectedDates = true;
}
}
}
// Function to update the text content of a given element with a specified date
function updateSelectDateText(elementId, text) {
const dateSpan = document.getElementById(elementId);
dateSpan.textContent = text;
}
// Function to update the state of the Clear Dates button
function updateClearDatesButton() {
if (departureDate || returnDate) {
clearDatesBtn.classList.remove("btn-disabled-txt");
} else {
clearDatesBtn.classList.add("btn-disabled-txt");
}
}
// Function to format a date as a string (e.g., "Jul 27, 2023")
function formatDate(day, month, year) {
const date = new Date(year, month, day);
// return date.toLocaleDateString('default');
const formattedDay = String(date.getDate()).padStart(2, '0');
const formattedMonth = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const formattedYear = String(date.getFullYear());
// console.log(formattedDay,"-",formattedMonth,"-",formattedYear);
return `${formattedDay}-${formattedMonth}-${formattedYear}`;
}
// Create and display the calendar for the next 12 months
const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();
for (let i = currentMonth; i < currentMonth + 12; i++) {
createCalendar(i % 12, currentYear + Math.floor(i / 12));
}
</script>`