html部分:
<div id="date" class="wrapper"></div>
css部分:
.wrapper {
position: relative;
width: 350px;
margin: 100px auto;
}
.day-wrap {
display: flex;
flex-wrap: wrap;
}
.item {
display: inline-block;
width: 50px;
height: 40px;
line-height: 40px;
text-align: center;
}
.day-item {
width: 49px;
margin-right: 1px;
margin-bottom: 1px;
padding: 2px 0;
background-color: pink;
}
h3 {
text-align: center;
}
.btn {
position: absolute;
top: 0;
}
.btn-left {
left: 0;
}
.btn-right {
right: 0;
}
.active {
background-color: skyblue;
}
js部分:
var weekList = [
{index: 0, text: '周日'},
{index: 1, text: '周一'},
{index: 2, text: '周二'},
{index: 3, text: '周三'},
{index: 4, text: '周四'},
{index: 5, text: '周五'},
{index: 6, text: '周六'}
];
// 获取当前 年, 月, 日
var dateInfo = new Date();
var year = dateInfo.getFullYear()
var nowYear = year
var month = dateInfo.getMonth() + 1
var nowMonth = month
var day = dateInfo.getDate()
setCalendar(year, month, day)
function setCalendar(year, month) {
var days = new Date(year, month, 0).getDate() // 每月几天
var obj = {
month: month,
dayList: []
}
for (var index = 1; index <= days; index++) {
var dayWeek = new Date(year, month-1, index).getDay()
obj.dayList.push({date: index, week: dayWeek})
}
render(obj, days)
}
function render (obj, days) {
var dom = document.getElementById('date')
// 添加按钮
var _html = '<button class="btn btn-left" id="btnLeft">上月</button><button class="btn btn-right" id="btnRight">下月</button>'
// 添加年月
_html += '<h3>' + year +'-' + obj.month + '</h3>' + '<div> <div class="week">'
// 添加星期
for (var index = 0; index < weekList.length; index++) {
var item = weekList[index]
_html += ('<div class="item">' + item.text + '</div>')
}
_html += '</div><div class="day-wrap">'
// 添加开头空日期
for (let index = 0; index < obj.dayList[0].week; index++) {
_html += ('<div class="item day-item"></div>')
}
var lastEmpty = 7 - (obj.dayList[0].week + days) % 7
// 添加日期
for (var index = 0; index < obj.dayList.length; index++) {
var item = obj.dayList[index]
var active = ''
if (item.date == day && nowMonth == month && year == nowYear) {
active = 'active'
}
// 渲染日期
_html += ('<div class="item day-item '+ active + '">' + item.date + '</div>')
}
// 补上结尾空白日期
if (lastEmpty < 7) {
for (var index = 0; index < lastEmpty; index++) {
_html += ('<div class="item day-item"></div>')
}
}
_html += '</div></div>'
dom.innerHTML = _html
setEvent()
}
function setEvent() {
setTimeout(() => {
var left = document.getElementById('btnLeft')
var right = document.getElementById('btnRight')
left.addEventListener('click', function () {
if (month == 1) {
year = year - 1
month = 12
} else {
month = month - 1
}
setCalendar(year, month, day)
})
right.addEventListener('click', function () {
if (month == 12) {
year = year + 1
month = 1
} else {
month = month + 1
}
setCalendar(year, month, day)
})
})
}
代码很简单~, 先这样再那样, 简单写的, 如果大家有指教就多多评论哦! 效果如下: