日历
html部分:
<h1></h1>
<button class="prev"><</button>
<button class="next">></button>
<div class="container">
<ul>
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
<ul class="contain"></ul>
</ul>
</div>
css样式部分:
* {
padding: 0;
margin: 0;
list-style: none;
}
.container{
margin-top:50px ;
}
.container ul {
display: flex;
flex-wrap: wrap;
width: 352px;
text-align: center;
border: 1px solid #ccc;
}
.container li {
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
}
.contain li:not(.disabled):hover {
background-color: steelblue;
}
li.active {
background: darkcyan;
color: #fff;
}
.contain {
display: flex;
flex-wrap: wrap;
}
li.disabled {
background: #eee;
color: #ccc;
cursor: not-allowed;
}
button{
position: absolute;
top: 20px;
}
.prev{
left:300px ;
}
.next{
left: 320px;
}
js部分:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
let now = new Date()
let totalDays = 0
let today = now.getDate()//获取今天
let global_month = now.getMonth() + 1//获取月份
let global_year = now.getFullYear()//获取年份
$('.prev').click(function(){//当点击前面的按钮时,获取的月份-1
now.setMonth(now.getMonth()-1)
go()
})
$('.next').click(function(){//当点击下一个按钮时,获取的月份+1
now.setMonth(now.getMonth()+1)
go()
})
go()
function go() {
$('.contain').empty()//清除
let title= `${now.getFullYear()}/${now.getMonth()+1}`;//获得现在是xx年xx月
$('h1').html(title)
let month=now.getMonth()+1//重新获取
let year=now.getFullYear()
switch (month) {//判断每个月多少天
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
totalDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
totalDays = 30;
break;
default:
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {//判断是闰年还是平年
totalDays = 29
} else {
totalDays = 28
}
break;
}
for (let i = 1; i <= totalDays; i++) {//循环生成li
let li = $('<li/>').text(i)
//如果是今天就高亮
if (i === today && year === global_year && month === global_month) li.addClass('active')
$('.contain').append(li)
}
// 获取1号
now.setDate(1)
let firstDay = now.getDay()
for (let i = 0; i < firstDay; i++) {
now.setDate(now.getDate() - 1) //在1号前面添加
let li = $('<li/>').text(now.getDate()).addClass('disabled')//添加不可选中的样式
$('.contain').prepend(li)
}
now.setDate(now.getDate() + firstDay) //恢复当月
now.setDate(totalDays)
let lastDay = 6 - now.getDay()
for (let i = 0; i < lastDay; i++) {
now.setDate(now.getDate() + 1)
let li = $('<li/>').text(now.getDate()).addClass('disabled')
$('.contain').append(li)
}
now.setDate(now.getDate() - lastDay)
now.setDate(1)
}
})
如图所示: