html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>日曆插件</title>
<link rel="stylesheet" href="./css/reset.css">
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div class="show">
<button id="pre">上月</button>
<span id="showtime">2019-01</span>
<button id="next">下月</button>
</div>
<div class="box" id="box">
</div>
</body>
<script>
function getMonthDay(date){
date=new Date(date.valueOf())
date.setDate(1);
return date
}
function getMonthLastDay(date){
date=new Date(date.valueOf())
date.setMonth(date.getMonth()+1);
date.setDate(0);
return date
}
function getMonth(date){
var arr=[]
var _date=getMonthDay(date)
var dataLast=getMonthLastDay(date).getDate()
arr.push(new Date(_date.valueOf()))
for(var i =1;i<dataLast;i++){
_date.setDate(_date.getDate()+1)
arr.push(new Date(_date.valueOf()))
}
_date=getMonthDay(date)
var forln=_date.getDay()
for(var i=0;i<forln;i++){
_date.setDate(_date.getDate()-1)
arr.unshift(new Date(_date.valueOf()))
}
_date=getMonthLastDay(date)
forln=_date.getDay()
for(var i=forln;i<6;i++){
_date.setDate(_date.getDate()+1)
arr.push(new Date(_date.valueOf()))
}
return arr
}
function renderTable(monthDateArr,date){
document.getElementById("showtime").innerHTML=`${date.getFullYear()}-${date.getMonth()+1}`
var table=document.createElement('table')
var trTh=document.createElement('tr')
trTh.innerHTML=`
<th>週日</th>
<th>週一</th>
<th>週二</th>
<th>週三</th>
<th>週四</th>
<th>週五</th>
<th>週六</th>
`
table.appendChild(trTh)
var tr=document.createElement('tr')
for(let i in monthDateArr){
var td=document.createElement('td')
td.innerHTML=monthDateArr[i].getDate()
tr.appendChild(td)
if((i*1+1)%7===0){
table.appendChild(tr)
tr=document.createElement('tr')
}else if(i == monthDateArr.length-1){
table.appendChild(tr)
}
}
document.getElementById("box").innerHTML=table.outerHTML
}
var date=new Date()
document.getElementById('pre').onclick=function(){
date.setDate(1)
date.setMonth(date.getMonth()-1)
renderTable(getMonth(date),date)
}
document.getElementById('next').onclick=function(){
date.setDate(1)
date.setMonth(date.getMonth()+1)
rrenderTable(getMonth(date),date)
}
renderTable(getMonth(date),date)
</script>
</html>
css代碼
.box{
width: 700px;
margin: 0 auto;
box-sizing: border-box;
padding: 0 1px;
}
table{
width: 100%;
}
th,td{
width:100px;
text-align: center;
}
th{
height: 30px;
line-height: 30px;
background: #e0e5e5;
}
td{
height: 70px;
line-height: 70px;
background: #f3f5f5;
}
.show{
display: flex;
align-items: center;
justify-content: center;
}