【html css js】实现一个简易日历

2023-02-25,,,,

——【效果预览】

实现了日历最基础的功能,当前日期红色显示,可通过上方的左右按钮查看上一月或下一月的日期。

——【代码部分】

1. HTML

 <body>
<div class="cldBody">
<table>
<thead>
<tr>
<td colspan="7">
<div class="top">
<span id="left">&lt;</span>
<span id="topDate"></span>
<span id="right">&gt;</span>
</div>
</td>
</tr>
<tr id="week" >
<td>日</td>
<td>一</td>
<td>二</td>
<td>三</td>
<td>四</td>
<td>五</td>
<td>六</td>
</tr>
</thead>
<tbody id="tbody" ></tbody>
</table>
</div>
</body>

2. CSS

 <style type="text/css">
.cldBody{background:#f7f7f7;width: 420px;margin: 10px auto;}
.cldBody .top{height: 60px;line-height: 60px;text-align: center;position: relative;}
#topDate{font-size: 24px;}
#week td{font-size: 15px;}
td{width: 60px; height: 60px;line-height: 60px;text-align: center;font-size: 20px;}
#tbody td:hover{background: #ededed;cursor: pointer;}
.curDate{color: red;font-weight: bold;}
#left,#right{width: 60px;height: 60px;position: absolute;cursor: pointer;}
#left{left: 0;}
#right{right: 0;}
#left:hover, #right:hover{background-color: rgba(30, 30, 30, 0.2);}
</style>

【效果图】:

3.JS部分【博主引用了jq框架】

——1. 引入jq

  <script src="js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>

——2. 添加月份到顶部

 var date = new Date();
var year = date.getFullYear();
var nowyear = date.getFullYear();
var month = date.getMonth()+1;
var nowmonth = date.getMonth()+1;
var dateday = date.getDate();
var todateHtml = year + '年'+ month + '月';
$('#topDate').text(todateHtml)

——3. 添加日历函数

 function showcld(){
var monthDay = [31,28,31,30,31,30,31,31,30,31,30,31]; // 创建数组存放每个月有多少天 ,默认2月为28天
// 判断闰年
if(year % 4 == 0 && year %100 != 0 || year % 400 == 0){
monthDay[1] = 29;
}
// 计算每个月的天数
var days = monthDay[month-1];
// 判断每月第一天为周几
date.setYear(year); //某年
date.setMonth(month-1); //某年的某月
date.setDate(1); // 某月的某天
var weekday = date.getDay(); // 判断某天是周几
// 补齐一号前的空格
var tbodyHtml = '<tr>';
for(var i = 0; i<weekday; i++){
tbodyHtml += "<td></td>";
}
// 补齐每月的日期
var changLine = weekday;
var tagClass = '';
for(i=1; i<=days; i++){//每一个日期的填充
if(year == nowyear && month == nowmonth && i == dateday) {
tagClass = "curDate";//当前日期对应格子
}else{
tagClass = "isDate";
}
tbodyHtml += "<td class=" + tagClass + ">" + i + "</td>";
changLine = (changLine+1)%7;
if(changLine == 0 && i != days){//是否换行填充的判断
tbodyHtml += "</tr><tr>";
}
}
$('#tbody').empty(); // 清空原有的内容
$('#tbody').append(tbodyHtml); //添加当前月份的日期内容
}

——4.添加点击按钮事件

 // 设置按钮点击事件
$('#left').click(function(){
month = month-1;
if(month < 1){
month = 12;
year--;
}
var todateHtml = year + '年'+ month + '月';
$('#topDate').text(todateHtml);
showcld();
}); $('#right').click(function(){
month = month+1;
if(month > 12){
month = 1;
year++;
}
var todateHtml = year + '年'+ month + '月';
$('#topDate').text(todateHtml);
showcld();
})
showcld(); //页面加载后执行函数

html css js】实现一个简易日历的相关教程结束。