效果图:
html代码:
<div id="date">
<p>
<span id="prev">上一月</span>
<span id="year">2022</span>
<span id="next">下一月</span>
</p>
<h5 id="month">七月</h5>
<ul id="title">
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
</ul>
<ul id="days"></ul>
</div>
css代码:
*{
margin: 0px;
padding: 0px;
}
#date{
width: 300px;
padding: 10px;
border: 1px solid #000000;
}
#date>p{
display: flex;
}
#date>p>span{
display: inline-block;
width: 100px;
text-align: center;
}
#month{
text-align: center;
font-weight: 400;
}
#title{
list-style: none;
display: flex;
width: 300px;
padding: 0;
margin: 0;
}
#title>li{
flex: 1;
text-align: center;
width: 100%;
background: #C0C0C0;
}
#days{
height: 250px;
margin-top: 10px;
}
#days>li{
list-style: none;
text-align: center;
float: left;
width: 42.28px;
height: 42.28px;
}
.active{
color:orange;
}
javascript代码:
let date=new Date();
add();
function add(){
let year=date.getFullYear()
document.getElementById("year").innerText=year
let month=date.getMonth();
let monthArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
document.getElementById("month").innerText=monthArr[month];
// 获取当天的天数
let currentDay=date.getDate()
// 获取每个月的第一天是周几
let week=new Date(year,month,1).getDay();
let html=""
// 代表前面空白的li标签
for(var i=0;i<week;i++){
console.log(i)
html+="<li></li>"
}
// 获取每个月的天数的最后一天
let lastDay=new Date(year,month+1,0).getDate()
for(var i=1;i<=lastDay;i++){
if(i==currentDay){
html+=`<li class="active">${i}</li>`
}else{
html+=`<li>${i}</li>`
}
}
document.getElementById("days").innerHTML=html
}
document.getElementById("prev").onclick=function(){
date.setMonth(date.getMonth()-1)
add();
}
document.getElementById("next").onclick=function(){
date.setMonth(date.getMonth()+1)
add();
}
关键代码是
new Date(year,month,1).getDay() 获取每个月的第一个天是星期几
new Date(year,month+1,0).getDate() 获取每个月的最后一天是几号