整理电脑时,发现很久之前用JS写的一个日历

发到这里来共享......


好的,以下是用 JavaScript 实现的简单日历: ```html <!DOCTYPE html> <html> <head> <title>日历</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; } table { border-collapse: collapse; margin: 20px auto; } td { border: 1px solid #ccc; padding: 10px; text-align: center; width: 50px; height: 50px; } .today { background-color: #ccc; } </style> </head> <body> <h1>日历</h1> <table> <thead> <tr> <th>日</th> <th>一</th> <th>二</th> <th>三</th> <th>四</th> <th>五</th> <th>六</th> </tr> </thead> <tbody id="calendar-body"> </tbody> </table> <script> // 获取当前日期 let today = new Date(); // 获取当前月份的第一天 let firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1); // 获取当前月份的最后一天 let lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0); // 获取当前月份有多少天 let numOfDays = lastDayOfMonth.getDate(); // 获取当前月份第一天是星期几 let firstDayOfWeek = firstDayOfMonth.getDay(); // 创建一个空的数组,用于存储日历中的日期 let calendarDates = []; // 将空的数组填充满当前月份的所有日期 for (let i = 1; i <= numOfDays; i++) { calendarDates.push(i); } // 补充当前月份第一天之前的日期 while (firstDayOfWeek > 0) { calendarDates.unshift(""); firstDayOfWeek--; } // 补充当前月份最后一天之后的日期 while (calendarDates.length < 42) { calendarDates.push(""); } // 将日历日期渲染到页面上 let calendarBody = document.getElementById("calendar-body"); let html = ""; for (let i = 0; i < calendarDates.length; i++) { if (i % 7 === 0) { html += "<tr>"; } let className = ""; if (calendarDates[i] === today.getDate()) { className = "today"; } html += `<td class="${className}">${calendarDates[i]}</td>`; if (i % 7 === 6) { html += "</tr>"; } } calendarBody.innerHTML = html; </script> </body> </html> ``` 这个日历可以显示当前月份的所有日期,并且高亮显示今天的日期。在页面上运行代码,你会看到一个类似下面这样的日历: ``` 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值