日期:2014-05-16  浏览次数:20394 次

JS实现日历-1

日历控件经常在平常的工作中使用到,他的实现方法以前并没有深入研究,今天写了一个简单的,知识打印出日历的基本结构,以后会添加更强大的功能。请关注后面的文章.

?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> 日历 </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <style type="text/css">
		
  </style>
 
 </head>

 <body>
	<div	id="calendar">
	
	</div>
 </body>
</html>
 <script type="text/javascript">
  <!--
	function Calendar(year,month,day){

		if(typeof year!="number"||typeof month !="number"){
			throw new Error("参数必须为整形");
		}
		this.year=year;
		this.month=month;
		this.day=day;
		this.daysOfMonth=[31,0,31,30,31,30,31,30,30,31,30,31]
		Calendar.prototype.getDaysOfMonth=function(){
			var value=this.daysOfMonth[this.month-1];
			if(value==0){
				if((this.year%4==0&&this.yea%100!=0)||(this.yea%400==0))
                {
                    value=29
                }
                else
                {
                    value=28
                }
			}
			return value;
		};
		//获取本月的第一天是星期几
		Calendar.prototype.getDayBeginOfMonth=function(){
			var today=new Date();
			today.setYear(this.year);
			today.setMonth(this.month-1);
			today.setDate(1);
			return today.getDay();
		};
		//获取本月的最后一天是星期几
		Calendar.prototype.getDayEndOfMonth=function(){
			var today=new Date();
			today.setYear(this.year);
			today.setMonth(this.month-1);
			today.setDate(this.getDaysOfMonth());
			return today.getDay();
		};
		//获取日历数组
		Calendar.prototype.getCalData=function(){
			var days=this.getDaysOfMonth();
			var firstDay=this.getDayBeginOfMonth();
			var lastDay=this.getDayEndOfMonth();
			var data=new Array(firstDay+days+6-lastDay);
			for(var i=0,j=0;i<data.length;i++){
				if(i<firstDay||i>=(days+firstDay)){
					data[i]="";
				}else{
					j++;
					data[i]=j;
				}
			}
			return data;
			
		};
	}
	var cal=new Calendar(2012,3);
	var data=cal.getCalData();
	var calendarDom=document.getElementById("calendar");
	var table=document.createElement("table");
	for(var i=0;i<data.length;i++){
		if(i%7==0){
			table.insertRow(-1);
		}
		var curRow=table.rows[parseInt(i/7)];
		var curCell=document.createElement("td");
		curCell.innerHTML=data[i];
		curRow.appendChild(curCell);
		
	}
	
	calendarDom.appendChild(table);
  //-->
  </script>
?

?

?

?

?

?