一步一步理解日历calendar(一)

这里开始介绍一个史上最简单的日历,只显示当月,但是它是一个雏形,会一步一步完善,效果如下:

一步一步理解日历calendar(一)
                         (够简单,够帅气)

实现方式如下:
MaxDayOfDate作用是返回某月的最大天数
GetDayOfWeek作用是当月的第一天是星期几 星期一:1,星期二:2,星期三:3,星期四:4,星期五:5,星期六:6星期日:7
calendar作用是创造日历

一步一步理解日历calendar(一)一步一步理解日历calendar(一)View Code
 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>一步一步理解日历calendar(一)</title>
5 <style type="text/css">
6 *{ margin:0px; padding:0px;}
7 .canlender{ text-align:center}
8 .canlender th{ background-color:#6666FF}
9 .canlender .today{ background-color:Orange; color:Red; font-weight:bold}
10 </style>
11 <script type="text/javascript">
12 window.onload = function () {
13 function MaxDayOfDate(year, month) {
14 switch (month) {
15 case 1:
16 case 3:
17 case 5:
18 case 7:
19 case 8:
20 case 10:
21 case 12:
22 return 31;
23 case 4:
24 case 6:
25 case 9:
26 case 11:
27 return 30;
28 case 2:
29 if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
30 return 29;
31 }
32 else {
33 return 28;
34 }
35 default:
36 return 0;
37 }
38 }
39
40 function GetDayOfWeek(year, month) {
41 if (0 == (new Date(year, month, 1)).getDay()) {
42 return 7;
43 }
44 else {
45 return (new Date(year, month, 1)).getDay();
46 }
47 }
48
49
50 function calendar(obj) {
51 var today = new Date();
52 var year = today.getFullYear();
53 var month = today.getMonth();
54 var day = today.getDate();
55 var days = MaxDayOfDate(year, month + 1);
56 var week = GetDayOfWeek(year, month);
57 var html = "<table class='canlender' border='1px'><thead><tr><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th><th>星期日</th></tr></thead>";
58 for (var i = 1; i <= 42; i++) {
59 if (1 == i % 7 || 1 == i) {
60 html += "<tr>";
61 }
62 if (i >= week && i <= (week + days - 1)) {
63 if (day == i) {
64 html += "<td class='today'>" + parseInt(i - week + 1) + "</td>";
65 } else if (day < i - week) {
66 html += "<td>" + parseInt(i - week + 1) + "</td>";
67 }
68 else {
69 html += "<td>" + parseInt(i - week + 1) + "</td>";
70 }
71 if (0 == i % 7 || 7 == i) {
72 html += "</tr>";
73 }
74 }
75 else {
76 html += "<td>&nbsp;</td>";
77 }
78 }
79 html += "</table>";
80 obj.innerHTML = html;
81 }
82
83 calendar(document.getElementById("test"));
84 }
85 </script>
86 <div id="test">
87 </div>
88 </head>
89 <body>
90 </body>
91 </html>

 

上一篇:一步一步理解日历calendar(二)


下一篇:一步一步理解拖拽Drag(五)