Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说手撕代码--JavaScript实现年历「建议收藏」,希望能够帮助你!!!。
效果图:
方案描述:
开发工具:Hbuilder X(html + javasc)
代码(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>
function calendar(y) {
var html = '<div class = "box">';
// week day of 2020-1-1?
var w = new Date(y,0).getDay();
console.log("w is: " + w);
for (var m = 1; m <= 12; ++m) {
html += '<table>' ;
// 2 lines --table head
html += '<tr class = "title"> <th colspan = "7">' + y + ' year ' + m + ' month </th> </tr>';
html += '<tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
var maxDay = new Date(y,m,0).getDate();
html += '<tr>'
// print each week of current month
for (var d = 1; d <= maxDay; d++) {
if(w && d == 1) {
html += '<td colspan = "' + w + '"> </td>';
}
html += '<td>' + d + '</td>';
if (w == 6 && d != maxDay) {
html += '</tr><tr>';
} else if(d == maxDay) {
html += '</tr>';
}
w = ((w+1) > 6 ? 0 : (w+1));
}
html += '</table>';
}
html +='</div>';
return html;
}
var year = parseInt(prompt('输入年份:', '2020'));
document.write(calendar(year));
</script>
</head>
<body></body>
</html>