How to use javascript to make an annual calendar: [function calendar(y){ var w = new Date(y,0).getDay(); var html = '
';for(m =1;m<...>The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.
If we need to display specific items of a certain month on a web page, we often need to use the calendar component. Calendar components usually have many ready-made class libraries, so how do we develop a calendar ourselves? The following shows you a very Let’s take a look at the classic calendar component!
HTML:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>制作年历</title> <style> body{text-align:center;} .box{margin:0 auto;width:880px;} .title{background: #ccc;} table{height:200px;width:200px;font-size:12px;text-align:center;float:left;margin:10px;font-family:arial;} </style> <script src="calendar.js"></script> <script> var year = parseInt(prompt('输入年份:','2019'));//制作弹窗 document.write(calendar(year));//调用函数生成指定年份的年历 </script> </head> <body> </body> </html>Copy after logincalendar.js
function calendar(y){ //获取指定年份1月1日的星期数值 var w = new Date(y,0).getDay(); var html = '<div class="box">'; //拼接每个月份的表格 for(m=1;m<=12;m++){ html += '<table>'; html += '<tr class="title"><th colspan="7">' + y + '年' +m+' 月</th></tr>'; html += '<tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>' //获取每个月份共有多少天 var max = new Date(y,m,0).getDate(); html += '<tr>';//开始<tr>标签 for (d=1;d<=max;d++){ if(w && d== 1){//如果该月的第1天不是星期日,则填充空白 html += '<td colspan ="' + w + '"> </td>'; } html += '<td>' +d+ '</td>'; if(w == 6 && d != max){//如果星期六不是该月的最后一天,则换行 html += '</tr><tr>'; }else if(d==max){//该月的最后一天,闭合</tr>标签 html += '</tr>'; } w = (w+1>6) ? 0 : w+1; } html += '</table>'; } html += '</div>'; return html; }Copy after loginFinal effect:
Recommended learning: javascript video tutorial
The above is the detailed content of How to make an annual calendar using javascript. For more information, please follow other related articles on the PHP Chinese website!