用html实现输入一个年份显示出这个年份每个月的日历
时间: 2024-02-22 16:59:02 浏览: 105
好的,以下是一个简单的HTML代码,通过JavaScript实现输入一个年份,显示出这个年份每个月的日历:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>年历</title>
<style>
table {
border-collapse: collapse;
margin: auto;
margin-bottom: 30px;
}
td {
width: 30px;
height: 30px;
text-align: center;
vertical-align: middle;
border: 1px solid black;
}
thead td {
background-color: #ccc;
}
.today {
background-color: #f00;
}
</style>
</head>
<body>
<h1>年历</h1>
<label for="year">请输入年份:</label>
<input type="number" id="year" min="1900" max="2100" step="1">
<button id="btn">显示</button>
<div id="calendar"></div>
<script>
var btn = document.getElementById('btn');
btn.onclick = function() {
var year = document.getElementById('year').value;
var calendar = document.getElementById('calendar');
calendar.innerHTML = '';
for (var month = 1; month <= 12; month++) {
var days = new Date(year, month, 0).getDate();
var week = new Date(year, month - 1, 1).getDay();
var table = document.createElement('table');
calendar.appendChild(table);
var caption = document.createElement('caption');
caption.innerHTML = year + '年' + month + '月';
table.appendChild(caption);
var thead = document.createElement('thead');
table.appendChild(thead);
var tr = document.createElement('tr');
thead.appendChild(tr);
var td = document.createElement('td');
td.innerHTML = '日';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '一';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '二';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '三';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '四';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '五';
tr.appendChild(td);
var td = document.createElement('td');
td.innerHTML = '六';
tr.appendChild(td);
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (var i = 1 - week; i <= days; i += 7) {
var tr = document.createElement('tr');
tbody.appendChild(tr);
for (var j = i; j < i + 7; j++) {
var td = document.createElement('td');
if (j > 0 && j <= days) {
td.innerHTML = j;
if (j == new Date().getDate() && month == new Date().getMonth() + 1) {
td.className = 'today';
}
}
tr.appendChild(td);
}
}
}
}
</script>
</body>
</html>
```
这个示例代码使用了JavaScript来实现,通过输入年份,点击“显示”按钮即可显示出这个年份每个月的日历。你可以根据实际需要进行修改。
阅读全文