这是做好后的效果。不是很美观,还可以进一步完善。
html+css代码如下:
<!DOCTYPE html>
<html>
<head>
<title>日历</title>
<style type="text/css">
#div1{
width:425px;
height:420px;
border:1px solid gray;
}
#div2{
width: 390px;
height: 390px;
margin:auto;
margin-top: 15px;
}
#div21{
width: 220px;
height: 72px;
margin:auto;
line-height: 72px;
margin:auto;
}
#div22{
width: 355px;
height: 310px;
margin:auto;
}
#table1{
width: 355px;
height: 30px;
border-spacing: 30px 33px;
}
#table2{
width: 355px;
height: 30px;
line-height: 30px;
border-spacing: 30px 0px;
}
</style>
</head>
<body>
<div id="div1">
<div id="div2">
<div id="div21">
<button onclick="lastMon()">上一月</button>
<text id="yearAndMon"></text>
<button onclick="nextMon()">下一月</button>
</div>
<div id="div22">
<table id="table2">
<tr>
<td>日</td>
<td>一</td>
<td>二</td>
<td>三</td>
<td>四</td>
<td>五</td>
<td>六</td>
</tr>
</table>
<table id="table1"></table>
</div>
</div>
</div>
<script type="text/javascript" src="rili.js"></script>
</body>
</html>
javascript代码如下:
var nowDate=new Date();
var nowYear=nowDate.getFullYear();
var nowMonth=nowDate.getMonth()+1;
//var month=(nowMonth<10?"0"+momth:month);
var text=document.getElementById("yearAndMon");
text.innerText=nowYear+"年"+nowMonth+"月";
var monthDays1=[31,29,31,30,31,30,31,31,30,31,30,31];
var monthDays2=[31,28,31,30,31,30,31,31,30,31,30,31]
function becomeDate(nowYear,nowMonth){
var dt=new Date(nowYear,nowMonth-1,1);
var firstDay=dt.getDay();
var table=document.getElementById("table1");
var monthDays=isRunNian();
var rows=5;
var cols=7;
var k=1;
for(var i=1;i<=rows;i++){
var tri=table.insertRow();
for(var j=1;j<=7;j++){
var tdi=tri.insertCell();
if(i==1&&i*j<firstDay+1)
tdi.innerHTML="";
else{
if(k>monthDays[nowMonth-1])
break;
tdi.innerHTML=k;
k++;
}
}
}
}
function lastMon(){
table1.innerHTML="";
var text=document.getElementById("yearAndMon");
if(nowMonth>1)
nowMonth=nowMonth-1;
else{
nowYear--;
nowMonth=12;
}
text.innerText=nowYear+"年"+nowMonth+"月";
becomeDate(nowYear,nowMonth);
}
function nextMon(){
table1.innerHTML="";
if(nowMonth<12)
nowMonth=nowMonth+1;
else{
nowYear++;
nowMonth=1;
}
var text=document.getElementById("yearAndMon");
text.innerText=nowYear+"年"+nowMonth+"月";
becomeDate(nowYear,nowMonth);
}
function isRunNian(){
if((nowYear%4==0||nowYear%400==0)&&nowYear%100!=0)
return monthDays1;
else
return monthDays2;
}
becomeDate(nowYear,nowMonth);
代码还存在很多不足之处,还请多多指教。