写一个日历组件,日历前加当前是第几周
时间: 2023-12-28 19:03:23 浏览: 26
这是一个简单的日历组件,使用JavaScript和HTML/CSS编写。它显示当前日期和时间,以及当前周的数字。
HTML代码:
```
<div id="calendar">
<div id="date"></div>
<div id="week"></div>
<table>
<thead>
<tr>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
</thead>
<tbody id="calendar-body"></tbody>
</table>
</div>
```
CSS代码:
```
#calendar {
font-family: Arial, sans-serif;
font-size: 14px;
width: 300px;
text-align: center;
}
#date {
font-size: 24px;
margin-bottom: 10px;
}
#week {
font-size: 16px;
margin-bottom: 10px;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 10px;
}
th, td {
padding: 5px;
border: 1px solid #ccc;
text-align: center;
}
th {
background-color: #eee;
}
td.today {
background-color: #ffc;
}
```
JavaScript代码:
```
// 获取DOM元素
const calendarBody = document.getElementById('calendar-body');
const dateElement = document.getElementById('date');
const weekElement = document.getElementById('week');
// 获取当前日期
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const date = today.getDate();
const day = today.getDay(); // 0-6,0表示星期日
// 获取当前周数
const startOfYear = new Date(year, 0, 1); // 当前年份的第1天
const diff = today.getTime() - startOfYear.getTime(); // 相差毫秒数
const week = Math.floor(diff / (1000 * 60 * 60 * 24 * 7)) + 1;
// 设置日期和周数
dateElement.innerHTML = `${year}-${month + 1}-${date}`;
weekElement.innerHTML = `Week ${week}`;
// 构建日历
const daysInMonth = new Date(year, month + 1, 0).getDate(); // 当前月份的天数
const firstDayOfMonth = new Date(year, month, 1).getDay(); // 当前月份的第1天是星期几
const lastDayOfMonth = new Date(year, month, daysInMonth).getDay(); // 当前月份的最后1天是星期几
const rows = Math.ceil((daysInMonth + firstDayOfMonth + (7 - lastDayOfMonth - 1)) / 7); // 日历表格的行数
let dateCounter = 1;
for (let i = 0; i < rows; i++) {
const row = document.createElement('tr');
for (let j = 0; j < 7; j++) {
const cell = document.createElement('td');
if (i === 0 && j < firstDayOfMonth) {
// 上个月的日期
const prevMonthDaysInMonth = new Date(year, month, 0).getDate();
const prevMonthDate = prevMonthDaysInMonth - (firstDayOfMonth - j - 1);
cell.innerHTML = prevMonthDate;
cell.classList.add('prev-month');
} else if (dateCounter > daysInMonth) {
// 下个月的日期
const nextMonthDate = dateCounter - daysInMonth;
cell.innerHTML = nextMonthDate;
cell.classList.add('next-month');
} else {
// 当前月份的日期
cell.innerHTML = dateCounter;
if (dateCounter === date) {
cell.classList.add('today');
}
dateCounter++;
}
row.appendChild(cell);
}
calendarBody.appendChild(row);
}
```
效果图:
![日历组件](https://i.imgur.com/Zz3e6X9.png)