<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
#box {
width: 280px;
height: 360px;
margin: 50px auto;
background-color: black;
color: aliceblue;
line-height: 40px;
}
#header {
height: 40px;
color: aliceblue;
line-height: 40px;
}
#header span {
float: left;
text-align: center;
margin-top: 10px;
line-height: 40px;
}
#prev,
#next {
width: 20%;
line-height: 40px;
cursor: pointer;
}
#current {
width: 60%;
line-height: 40px;
}
#week li {
width: 40px;
text-align: center;
float: left;
line-height: 40px;
}
#content li {
width: 40px;
text-align: center;
float: left;
line-height: 40px;
}
</style>
<div id="box">
<div id="header">
<span id="prev" data-tag="-1">上</span>
<span id="current"></span>
<span id="next" data-tag="1">下</span>
</div>
<ul id="week">
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
</ul>
<ul id="content">
<!-- <li>31</li>
<li>1</li>
<li>2</li> -->
</ul>
</div>
</body>
<script>
var date = new Date();
renderUl(getPrevDays(date), getCurrentDays(date));
renderHead(date)
prev.onclick = function() {
date.setMonth(date.getMonth() - 1);
renderUl(getPrevDays(date), getCurrentDays(date));
renderHead(date)
}
next.onclick = function() {
date.setMonth(date.getMonth() + 1);
renderUl(getPrevDays(date), getCurrentDays(date));
renderHead(date)
}
function renderHead(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
current.innerHTML = `${year}年${month}月${day}日`
}
function getPrevDays(date) {
var date = new Date(date);
date.setDate(1);
var week = date.getDay();
date.setDate(0);
var maxDay = date.getDate();
var list = [];
for (var i = maxDay - week + 1; i <= maxDay; i++) {
list.push(i)
}
return list;
}
function getCurrentDays(date) {
var date = new Date(date);
date.setDate(1);
date.setMonth(date.getMonth() + 1);
date.setDate(0)
var days = date.getDate();
var list = [];
for (var i = 1; i <= days; i++) {
list.push(i)
}
return list;
}
function renderUl(prevDays, currentDays) {
var oContent = document.querySelector('#content');
var html = '';
prevDays.forEach(function (item, index) {
html += `<li style="color: red">${item}</li>`
});
currentDays.forEach(function (item, index) {
html += `<li>${item}</li>`
});
for (var i = 1; i <= 42 - prevDays.length - currentDays.length; i++) {
html += `<li style="color: red">${i}</li>`
}
oContent.innerHTML = html;
}
</script>