简易 javascript 日历
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body, ul, li {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.calendar {
margin: 10px auto;
border: 1px solid;
width: 21rem;
}
.calendar > .header {
display: flex;
justify-content: space-between;
align-items: center;
margin: .5rem;
}
.calendar > .header > .middle {
text-align: center;
}
.calendar > ul {
list-style: none;
display: flex;
margin-bottom: .5rem;
}
.calendar > ul > li {
flex-basis: 3rem;
padding: .5rem;
text-align: center;
}
.calendar > ul.week {
background-color: darkgray;
}
.calendar > ul.date {
flex-wrap: wrap;
}
.calendar > ul.date > li.active {
color: red;
}
</style>
</head>
<body>
<div class="calendar">
<div class="header">
<a class="prev" href="javascript:" title="上一月">上一月</a>
<div class="middle">
<div class="year"></div>
<div class="month"></div>
</div>
<a class="next" href="javascript:" title="下一月">下一月</a>
</div>
<ul class="week">
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
</ul>
<ul class="date"></ul>
</div>
<script>
var date = new Date();
function calendar() {
var year = date.getFullYear(),
month = date.getMonth(),
week = date.getDay(),
day = date.getDate(),
monthStr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'][month],
weekDays = new Date(year, month, 1).getDay(),
days = new Date(year, month + 1, 0).getDate();
// 插入年
document.getElementsByClassName('year')[0].innerHTML = year;
// 插入月
document.getElementsByClassName('month')[0].innerHTML = monthStr;
// 插入日
var dateStr = '', style;
for (var i = 0; i < weekDays; i++) dateStr += `<li></li>`;
for (var i = 1; i <= days; i++) {
style = '';
if (i === new Date().getDate() && year === new Date().getFullYear() && month === new Date().getMonth()) {
style = ' class="active"';
}
dateStr += `<li${style}>${i}</li>`;
}
document.getElementsByClassName('date')[0].innerHTML = dateStr;
}
window.onload = calendar;
document.getElementsByClassName('prev')[0].onclick = function () {
date.setMonth(date.getMonth() - 1);
calendar();
}
document.getElementsByClassName('next')[0].onclick = function () {
date.setMonth(date.getMonth() + 1);
calendar();
}
</script>
</body>
</html>