-
看效果图
- 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js 简单日历</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
.calendar{
border-radius: 10px;
width: 400px;
margin:100px auto 0;
box-shadow: 0 0 15px 5px #888;
padding: 20px 0;
box-sizing: border-box;
}
.calendar>ul{
display: flex;
justify-content: space-around;
margin-bottom: 20px;
color: #4A8AF4;
}
ul .month:hover{
color: #DD4F43;
cursor: pointer;
}
.calendar dl{
display:flex;
text-align:center;
height: 40px;
line-height: 40px;
color:#888;
font-weight:bold;
}
dl dd{
width: 14.3%;
}
.calendar ol{
display: flex;
flex-wrap: wrap;
}
ol li{
width: 14.28%;
text-align:center;
height: 40px;
line-height: 40px;
box-sizing: border-box;
border: #fff 2px solid;
}
ol .hover:hover{
border: #DD4F43 2px solid;
}
.today{
color: #DD4F43;
font-weight: bold;
}
</style>
</head>
<body>
<div class="calendar">
<ul>
<li class="month" onclick='prev()'>< 上一月</li>
<li class='date-show'></li>
<li class="month" onclick='next()'>下一月 ></li>
</ul>
<dl>
<dd>一</dd>
<dd>二</dd>
<dd>三</dd>
<dd>四</dd>
<dd>五</dd>
<dd>六</dd>
<dd>日</dd>
</dl>
<ol></ol>
</div>
<script type="text/javascript">
var object = {}
var arr = [1,2,3,4,5,6,7]
var newDate = new Date();
var year = newDate.getFullYear();
var month = newDate.getMonth();
var monthSub = month;
var date = newDate.getDate();
var dateShow = document.getElementsByClassName('date-show')[0];
function getMyMonth(mon) {
var lastDay = new Date(year,mon+1,0).getDate();
var weekNum = new Date(year,mon,1).getDay();
let y = new Date(year,mon).getFullYear()
let m = new Date(year,mon).getMonth()
dateShow.innerText = y+"年"+(m+1)+"月"
var prevDays = '';
var days = '';
if(weekNum == 0) weekNum = 7;
for(i = 1; i < weekNum; i ++){
prevDays += "<li></li>"
}
for(i = 1; i <= lastDay; i ++){
if(y == year && m == month && i == date){
days += "<li class='today hover'>" + i + "</li>"
}else{
days += "<li class='hover'>" + i + "</li>"
}
}
var ol = document.getElementsByTagName('ol')[0];
ol.innerHTML = prevDays + days;
}
getMyMonth(month);
function prev(){
getMyMonth(-- monthSub);
}
function next(){
getMyMonth(++ monthSub);
}
</script>
</body>
</html>