<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>Document</title><style>* {padding: 0;margin: 0;list-style: none;}.container {width: 350px;border: 1px solid #ccc;margin: 50px auto;}.container li {width: 50px;height: 50px;line-height: 50px;text-align: center;cursor: pointer;}.container li:not(.disabled):hover {background: rgb(44, 192, 192);color: #fff;}.container ul {display: flex;flex-wrap: wrap;}li.disabled {background: #eee;color: #ccc;cursor: not-allowed;}li.active {background: rgb(45, 217, 230);color: #fff;}button {width: 100px;height: 50px;line-height: 50px;text-align: center;font-size: 18px;background-color: rgb(218, 215, 78);color: #fff;border: none;}.btn {width: 250px;margin: 50px auto;display: flex;justify-content: space-around;}</style></head><body><div class=\"btn\"><button class=\"prev\">上个月</button><button class=\"next\">下个月</button></div><div class=\"container\"><ul><li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li></ul><ul class=\"day\"></ul></div><script src=\"../JQ/JQuery.js\"></script><script>$(function () {let totalDays = 0let now = new Date()let today = now.getDate()let global_month = now.getMonth() + 1let global_year = now.getFullYear()$(\'.prev\').click(function () {//点击获取上个月now.setMonth(now.getMonth() - 1)initCalendar()})$(\'.next\').click(function () {//点击获取下个月now.setMonth(now.getMonth() + 1)initCalendar()})function initCalendar() {$(\'.day\').empty()let month = now.getMonth() + 1let year = now.getFullYear()switch (month) { //按月份判断多少天case 1:case 3:case 5:case 7:case 8:case 10:case 12:totalDays = 31break;case 4:case 6:case 9:case 11:totalDays = 30break;default:if ((year % 4 === 0 && year % 100 != 0) || year % 400 === 0) totalDays = 29else totalDays = 28break;}for (let i = 1; i <= totalDays; i++) { //循环添加 日let li = $(\'<li/>\').html(i)if (i === today && year === global_year && month === global_month) li.addClass(\'active\')$(\'.day\').append(li)}now.setDate(1) //将日期调至本月的一号let firstDay = now.getDay() //获取本月一号星期 几,即前面需要补几天for (let i = 0; i < firstDay; i++) {now.setDate(now.getDate() - 1) //得到前一天的日期,这时已经是上个月$(\'.day\').prepend($(\'<li/>\').html(now.getDate()).addClass(\'disabled\')) //补进日历}now.setDate(now.getDate() + firstDay)//设置回来当前日期now.setDate(totalDays) //将日期调至本月最后一天let lastDay = 6 - now.getDay() //算出后面添加的天数for (let i = 0; i < lastDay; i++) {now.setDate(now.getDate() + 1) //得到后一天的日期$(\'.day\').append($(\'<li/>\').html(now.getDate()).addClass(\'disabled\')) //补进日历}now.setDate(now.getDate()-lastDay)//设置回来当前日期now.setDate(1) // 设置成当月的一号}initCalendar()})</script></body></html>
js,jQuery创建日历
未经允许不得转载:爱站程序员基地 » js,jQuery创建日历