<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0px;padding: 0px;}
#container{width: 400px;height: 190px; border: 1px solid royalblue;margin: 0px auto;}
#container>div:first-child{width: 130px; margin: 0px auto;flex;}
#tbcal{border-collapse: collapse; width: 100%;}
#tbcal tr th,#tbcal tr td{border: 1px solid #ccc;}
</style>
<script type="text/javascript">
window.onload=function(){
initial();
document.getElementById("selyear").onchange=show;
document.getElementById("selmonth").onchange=show;
}
//显示日历
function show(){
var year=parseInt(document.getElementById("selyear").value);
var month=parseInt(document.getElementById("selmonth").value);
var days=getLastDay(month);
var dt=new Date();
dt.setFullYear(year);
dt.setMonth(month-1);
dt.setDate(1);
var week=dt.getDay();
var day01=0;
var table=document.getElementById("tbcal");
while(table.rows.length>1){
table.deleteRow(1);
}
//根据月天数与月一号星期打印日历
for (var i=0;i<7;i++) {
var row=table.insertRow(i+1);
if(i==0&&week!=0){
for (var j=0;j<7;j++) {
if(week>j){
var cell=row.insertCell(j);
cell.innerHTML=" ";
}else{
day01=j-week+1;
var cell=row.insertCell(j);
cell.innerHTML=day01;
}
}
}else{
for (var j=0;j<7;j++) {
if(day01<days){
day01++;
var cell=row.insertCell(j);
cell.innerHTML=day01;
}else{
var cell=row.insertCell(j);
cell.innerHTML=" ";
}
}
}
}
}
//根据月份计算次月的天数(此方法无法分辨闰月)
function getLastDay(month){
var dt=new Date();
dt.setMonth(month);
dt.setDate(0);
return dt.getDate();
}
function initial(){
for (var i=1970;i<=2050;i++) {
var option=document.createElement("option");
option.text=i;
document.getElementById("selyear").add(option);
}
for (var i=1;i<=12;i++) {
var option=document.createElement("option");
option.text=i;
document.getElementById("selmonth").add(option);
}
}
</script>
</head>
<body>
<div id="container">
<div>
<select id="selyear"></select>年
<select id="selmonth"></select>月
</div>
<div>
<table id="tbcal">
<tr> <th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th> <th>六</th></tr>
</table>
</div>
</div>
</body>
</html>
JS DOM对象打印日历
最新推荐文章于 2023-08-14 20:21:22 发布