';for(m=1;m <...]."/> ';for(m=1;m <...].">

Home  >  Article  >  Web Front-end  >  How to make an annual calendar using javascript

How to make an annual calendar using javascript

王林
王林Original
2021-11-02 16:35:304517browse

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<...>

How to make an annual calendar using javascript

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(&#39;输入年份:&#39;,&#39;2019&#39;));//制作弹窗
			document.write(calendar(year));//调用函数生成指定年份的年历
		</script>
	</head>
	<body>
	</body>
</html>

calendar.js

function calendar(y){
	//获取指定年份1月1日的星期数值
	var w = new Date(y,0).getDay();
	var html = &#39;<div class="box">&#39;;
	
	//拼接每个月份的表格
	for(m=1;m<=12;m++){
		html += &#39;<table>&#39;;
		html += &#39;<tr class="title"><th colspan="7">&#39; + y + &#39;年&#39; +m+&#39; 月</th></tr>&#39;;
		html += &#39;<tr><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>&#39;
		
		//获取每个月份共有多少天
		var max = new Date(y,m,0).getDate();
		
		html += &#39;<tr>&#39;;//开始<tr>标签
		for (d=1;d<=max;d++){
			if(w && d== 1){//如果该月的第1天不是星期日,则填充空白
				html += &#39;<td colspan ="&#39; + w + &#39;"> </td>&#39;;
			}
			html += &#39;<td>&#39; +d+ &#39;</td>&#39;;
			if(w == 6 && d != max){//如果星期六不是该月的最后一天,则换行
				html += &#39;</tr><tr>&#39;;
			}else if(d==max){//该月的最后一天,闭合</tr>标签
				html += &#39;</tr>&#39;;
			}
			w = (w+1>6) ? 0 : w+1;
		}
		html += &#39;</table>&#39;;
	}
	html += &#39;</div>&#39;;
	return html;
}

Final effect:

How to make an annual calendar using javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn