利用html,css和js制作简单日历
时间: 2023-10-04 18:04:06 浏览: 34
好的,以下是一个简单的日历实现:
HTML代码:
```html
<div class="calendar">
<div class="header">
<button id="prev">❮</button>
<h2 id="month"></h2>
<button id="next">❯</button>
</div>
<table>
<thead>
<tr>
<th>日</th>
<th>一</th>
<th>二</th>
<th>三</th>
<th>四</th>
<th>五</th>
<th>六</th>
</tr>
</thead>
<tbody id="calendar-body"></tbody>
</table>
</div>
```
CSS代码:
```css
.calendar {
font-family: 'Helvetica Neue', sans-serif;
margin: 50px auto;
width: 350px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #2196f3;
color: white;
padding: 10px;
}
table {
width: 100%;
border-collapse: collapse;
}
th {
height: 30px;
text-align: center;
font-weight: normal;
background-color: #f2f2f2;
}
td {
height: 50px;
text-align: center;
border: 1px solid #ddd;
}
.today {
background-color: #2196f3;
color: white;
}
```
JavaScript代码:
```javascript
const months = [
'一月',
'二月',
'三月',
'四月',
'五月',
'六月',
'七月',
'八月',
'九月',
'十月',
'十一月',
'十二月',
];
const calendar = document.querySelector('#calendar-body');
const monthTitle = document.querySelector('#month');
const prevButton = document.querySelector('#prev');
const nextButton = document.querySelector('#next');
let currentDate = new Date();
function generateCalendar(currentDate) {
// 获取当前月份的第一天
const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
// 获取当前月份的最后一天
const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
// 清空日历
calendar.innerHTML = '';
// 设置月份标题
monthTitle.textContent = `${months[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
// 生成日历表格
let date = 1;
for (let i = 0; i < 6; i++) {
const row = document.createElement('tr');
for (let j = 0; j < 7; j++) {
const cell = document.createElement('td');
if (i === 0 && j < firstDayOfMonth.getDay()) {
// 空白单元格
cell.textContent = '';
} else if (date > lastDayOfMonth.getDate()) {
// 空白单元格(超过当前月份的最后一天)
cell.textContent = '';
} else {
// 日期单元格
cell.textContent = date;
if (date === currentDate.getDate()) {
cell.classList.add('today');
}
date++;
}
row.appendChild(cell);
}
calendar.appendChild(row);
}
}
generateCalendar(currentDate);
prevButton.addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() - 1);
generateCalendar(currentDate);
});
nextButton.addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() + 1);
generateCalendar(currentDate);
});
```
在浏览器中打开 HTML 文件,就可以看到一个简单的日历了,可以通过左右箭头切换月份。