——【效果预览】
实现了日历最基础的功能,当前日期红色显示,可通过上方的左右按钮查看上一月或下一月的日期。
——【代码部分】
1. HTML
1 <body>
2 <div class="cldBody">
3 <table>
4 <thead>
5 <tr>
6 <td colspan="7">
7 <div class="top">
8 <span id="left"><</span>
9 <span id="topDate"></span>
10 <span id="right">></span>
11 </div>
12 </td>
13 </tr>
14 <tr id="week" >
15 <td>日</td>
16 <td>一</td>
17 <td>二</td>
18 <td>三</td>
19 <td>四</td>
20 <td>五</td>
21 <td>六</td>
22 </tr>
23 </thead>
24 <tbody id="tbody" ></tbody>
25 </table>
26 </div>
27</body>
2. CSS
1 <style type="text/css">
2 .cldBody{background:#f7f7f7;width: 420px;margin: 10px auto;}
3 .cldBody .top{height: 60px;line-height: 60px;text-align: center;position: relative;}
4 #topDate{font-size: 24px;}
5 #week td{font-size: 15px;}
6 td{width: 60px; height: 60px;line-height: 60px;text-align: center;font-size: 20px;}
7 #tbody td:hover{background: #ededed;cursor: pointer;}
8 .curDate{color: red;font-weight: bold;}
9 #left,#right{width: 60px;height: 60px;position: absolute;cursor: pointer;}
10 #left{left: 0;}
11 #right{right: 0;}
12 #left:hover, #right:hover{background-color: rgba(30, 30, 30, 0.2);}
13 </style>
【效果图】:
3.JS部分【博主引用了jq框架】
——1. 引入jq
1 <script src="js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
——2. 添加月份到顶部
1 var date = new Date();
2 var year = date.getFullYear();
3 var nowyear = date.getFullYear();
4 var month = date.getMonth()+1;
5 var nowmonth = date.getMonth()+1;
6 var dateday = date.getDate();
7 var todateHtml = year + '年'+ month + '月';
8 $('#topDate').text(todateHtml)
——3. 添加日历函数
1 function showcld(){
2 var monthDay = [31,28,31,30,31,30,31,31,30,31,30,31]; // 创建数组存放每个月有多少天 ,默认2月为28天
3 // 判断闰年
4 if(year % 4 == 0 && year %100 != 0 || year % 400 == 0){
5 monthDay[1] = 29;
6 }
7 // 计算每个月的天数
8 var days = monthDay[month-1];
9 // 判断每月第一天为周几
10 date.setYear(year); //某年
11 date.setMonth(month-1); //某年的某月
12 date.setDate(1); // 某月的某天
13 var weekday = date.getDay(); // 判断某天是周几
14 // 补齐一号前的空格
15 var tbodyHtml = '<tr>';
16 for(var i = 0; i<weekday; i++){
17 tbodyHtml += "<td></td>";
18 }
19 // 补齐每月的日期
20 var changLine = weekday;
21 var tagClass = '';
22 for(i=1; i<=days; i++){//每一个日期的填充
23 if(year == nowyear && month == nowmonth && i == dateday) {
24 tagClass = "curDate";//当前日期对应格子
25 }else{
26 tagClass = "isDate";
27 }
28 tbodyHtml += "<td class=" + tagClass + ">" + i + "</td>";
29 changLine = (changLine+1)%7;
30 if(changLine == 0 && i != days){//是否换行填充的判断
31 tbodyHtml += "</tr><tr>";
32 }
33 }
34 $('#tbody').empty(); // 清空原有的内容
35 $('#tbody').append(tbodyHtml); //添加当前月份的日期内容
36}
——4.添加点击按钮事件
1 // 设置按钮点击事件
2 $('#left').click(function(){
3 month = month-1;
4 if(month < 1){
5 month = 12;
6 year--;
7 }
8 var todateHtml = year + '年'+ month + '月';
9 $('#topDate').text(todateHtml);
10 showcld();
11 });
12
13 $('#right').click(function(){
14 month = month+1;
15 if(month > 12){
16 month = 1;
17 year++;
18 }
19 var todateHtml = year + '年'+ month + '月';
20 $('#topDate').text(todateHtml);
21 showcld();
22 })
23 showcld(); //页面加载后执行函数