原生js实现的简单日历 月历
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Title</title> <style type="text/css"> #dateMonth { width: 600px; margin-top: 50px; cursor: pointer } #dateMonth th { height: 40px; width: 40px; } #monthList { width: 600px; background-color: #9cd5ff; margin: 0 auto; } #dateMonth .today { background-color: #5dffa8; font-size: 20px; font-weight: bolder; color: red; } </style> </head> <body> <div id="monthList"> </div> <script type="text/javascript"> var now = new Date(); var nowYear = now.getFullYear(); var nowMonth = now.getMonth(); var nowDay = now.getDate(); var beginOfWeek = 0; //每周默认开始周几 var week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; createMonthList(nowMonth); /** * 生成日历 * @param inputMonth */ function createMonthList(inputMonth) { var date = new Date(nowYear, inputMonth, 1); var str = "<table border='1' cellspacing='0' id='dateMonth'>"; str += "<tr><th onclick='preMonth()'><<</th></th><th colspan='5'>" + date.getFullYear() + "年" + (parseInt(date.getMonth()) + 1) + "月</th><th onclick='nextMonth()'>>></th></tr>"; //var str3 = "<tr><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th><th>星期天</th></tr>"; var str3 = "<tr>"; for (var i = 0, len = week.length; i < len; i++) { str3 += "<th>" + week[(i + beginOfWeek) % 7] + "</th>"; } str3 += "</tr>"; //获取月的天数 var date2 = new Date(nowYear, inputMonth + 1, 0); var monthOfDay = date2.getDate(); //获取1号星期几, var day = (date.getDay() + (7 - beginOfWeek)) % 7; var sum = monthOfDay + day; var tr = ''; var dayNum = 1; while (sum % 7 != 0) { sum++; } for (var i = 1; i <= sum; i++) { if (i % 7 == 1) { tr += "<tr>"; } if (i <= day || dayNum > monthOfDay) { tr += "<th> </th>"; } else { if (date.getFullYear() == nowYear && date.getMonth() == nowMonth && nowDay == dayNum) { tr += "<th>" + dayNum + "</th>"; } else { tr += "<th>" + dayNum + "</th>"; } dayNum++; } if (i % 7 == 0) { tr += "</tr>"; } } var str2 = "</table>"; var hidden = "<input type='hidden' id='currentMonth' value='" + inputMonth + "' /> "; var all = str + str3 + tr + str2; document.getElementById('monthList').innerHTML = all + hidden; } //上一个月 function preMonth() { var currentMonth = document.getElementById("currentMonth").value; createMonthList(parseInt(currentMonth) - 1); } //下一个月 function nextMonth() { var currentMonth = document.getElementById("currentMonth").value; createMonthList(parseInt(currentMonth) + 1); } </script> </body> </html>