js日历,纯手工,多多指正
程序员文章站
2022-03-03 22:41:19
...
基本实现上一月下一月,时间关系,有些细节没有完善,纯手工,应该有其它更好的办法可以参考
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js日历</title>
<style>
.wrap {
width: 500px;
padding: 10px;
}
.tool_box {
height: 50px;
display: flex;
background: cornflowerblue;
justify-content: space-between;;
align-items: center;
}
.current {
display: flex;
flex-direction: column;
align-items: center;
}
.week {
height: 50px;
display: flex;
justify-content: space-around;
align-items: center;
background: #CCCCCC;
}
.days {
display: flex;
flex-wrap: wrap;
text-align: center;
}
.days div {
width: 71px;
height: 50px;
}
.current_day {
color: #FF0000;
}
</style>
</head>
<body>
<div class="wrap">
<div class="tool_box">
<div class="prev">上一月</div>
<div class="current">
<div class="year" id="year">年</div>
<div class="month" id="month">月</div>
</div>
<div class="next">下一月</div>
</div>
<div class="week">
<div class="week_item">日</div>
<div class="week_item">一</div>
<div class="week_item">二</div>
<div class="week_item">三</div>
<div class="week_item">四</div>
<div class="week_item">五</div>
<div class="week_item">六</div>
</div>
<div class="days" id="days">
</div>
</div>
<script>
var monthArr = [
'一月',
'二月',
'三月',
'四月',
'五月',
'六月',
'七月',
'八月',
'九月',
'十月',
'十一月',
'十二月'
]
function getDays(today) {
var month = today.getMonth();
var yearStr = today.getFullYear(); //当前年
document.querySelector('#year').textContent = yearStr;
var monthStr = monthArr[month]; //当前月
document.querySelector('#month').textContent = monthStr;
var date = today.getDate(); //当前日
var currentMonth = today.setDate(1);
var monthFirstDay = new Date(currentMonth); //本月1日
var currentMonthFirstWeek = monthFirstDay.getDay();
nextMonth = monthFirstDay.setMonth(month + 1);
prevMonth = monthFirstDay.setMonth(month - 1)
var currentMonthLastDay = new Date(nextMonth - 86400000)
var currentMonthLastDayStr = currentMonthLastDay.getDate();
var day = '';
for (let w = 0; w < currentMonthFirstWeek; w++) {
day += '<div></div>';
}
for (let i = 1; i <= currentMonthLastDayStr; i++) {
if (i == date) {
day += '<div class="current_day">' + i + '</div>';
} else {
day += '<div>' + i + '</div>';
}
}
document.querySelector('#days').innerHTML = day;
}
var today = new Date();
getDays(today);
document.querySelector('.next').onclick = function () {
today = new Date(nextMonth);
getDays(today)
}
document.querySelector('.prev').onclick = function () {
today = new Date(prevMonth);
getDays(today);
}
</script>
</body>
</html>