AI智能
改变未来

jQuery 手写日历

默认显示当月日历,点击左右切换可以选择月份:

HTML 部分:

<div class=\"box\"><div class=\"bar\"><div><span class=\"year\"></span>年<span class=\"month\"></span>月</div><div><span class=\"prev\"><</span><span class=\"next\">></span></div></div><ul class=\"head\"><li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li></ul><ul class=\"content\"></ul></div>

css 部分:

*{margin: 0;padding: 0;}.box{margin: 0 auto;}.head, .content{list-style: none;display: flex;flex-wrap: wrap;border: 1px solid lightseagreen;width: 364px;margin: 10px auto;}.head li,.content li{list-style: none;width: 50px;height: 50px;text-align: center;line-height: 50px;}.head li{border: 1px solid lightseagreen;}.content li{border: dashed 1px lightgrey;}.content li.dark{background-color: #d3d3d3a1;color: darkgray;}.active{background-color: lightseagreen;}.bar{width: 364px;height: 30px;line-height: 30px;margin: 10px auto 0;display: flex;justify-content: space-between;align-items: center;font-size: 20px;font-weight: bold;}.prev, .next{padding: 0 20px;cursor: pointer;}

JS 部分:

$(function () {let content = $(\'.content\');let totalDays;let now = new Date();let today = now.getDate();let thisYear = now.getFullYear();let thisMonth = now.getMonth() + 1;// 月份选择按钮$(\'.prev\').click(function () {now.setMonth(now.getMonth() - 1);setCalender();});$(\'.next\').click(function () {now.setMonth(now.getMonth() + 1);setCalender();});// 封装的生成日历方法function setCalender(){content.empty();let month = now.getMonth() + 1;let year = now.getFullYear();// 日历头上显示的月份$(\'.year\').html(year);$(\'.month\').html(month);// 判断每月天数switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:totalDays = 31;break;case 4:case 6:case 9:case 11:totalDays = 30;break;default:if((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0){totalDays = 29;}else{totalDays = 28;}}// 将当月的天数加进日历for(let i = 0; i< totalDays; i++){let li = $(\'<li/>\').html(i+1);if (i === today -1 && month === thisMonth && year === thisYear){li.addClass(\'active\')}content.append(li);}// 上一个月的天数补上now.setDate(1);  // 日期设置为 1 号let firstDay = now.getDay();  // 获取当月第一天是星期几for (let i = 0; i < firstDay; i++) {now.setDate(now.getDate() -1);let li = $(\'<li/>\').html(now.getDate()).addClass(\'dark\');content.prepend(li);}// 下个月的天数补上now.setDate(now.getDate() + firstDay + totalDays -1);  // 日期设为本月最后一天let lastDay = now.getDay();  // 获取最后一天是星期几for (let i = 0; i < 6 - lastDay; i++) {now.setDate(now.getDate() + 1);let li = $(\'<li/>\').html(now.getDate()).addClass(\'dark\');content.append(li);}// 将日期设置为当月1号,因为每个月都有 1 号now.setDate(now.getDate()- 8);  // 月份切回当月now.setDate(1);console.log(now)}setCalender();})
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » jQuery 手写日历