*{ padding: 0;margin: 0; } ul,ol{ list-style: none; } .rili{ width: 240px;height: 300px;margin: 50px auto;border: 1px solid #333; } #week{ width: 240px;height: 34px;line-height: 34px;text-align: center;font-size: 16px } #week li{ float: left;width: 34px;height: 34px;line-height: 34px; } #day{ width: 240px; } #day li{ float: left;width: 34px;height: 34px;line-height: 34px;text-align: center; } .active{ background: red; }
<div class="rili"> <div> <span id="prevY"><</span> <span id="year">2018</span> <span id="nextY">></span> </div> <div> <span id="prevM"><</span> <span id="month">一月</span> <span id="nextM">></span> </div> <ul id="week"> <li>日</li> <li>一</li> <li>二</li> <li>三</li> <li>四</li> <li>五</li> <li>六</li> </ul> <ul id="day"> </ul> </div>
<script> var date = new Date(); var yearC = date.getFullYear(); var monthC = date.getMonth(); var dayC = date.getDate(); time(); function time(){ document.getElementById("day").innerHTML = ""; var year = date.getFullYear(); var month = date.getMonth(); arr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"] document.getElementById("year").innerHTML = year; document.getElementById("month").innerHTML = arr[month]; var setDate = new Date(year,month,0); var setDay = setDate.getDate(); var setWeek = new Date(year,month,1).getDay(); for(var i=0;i<setWeek;i++){ var li = document.createElement("li"); li.innerHTML = ""; document.getElementById("day").append(li); } for(var i=1;i<=setDay;i++){ var li = document.createElement("li"); li.innerHTML = i; if(yearC == year && monthC == month && dayC == i){ li.className = "active" } document.getElementById("day").append(li); } document.getElementById("prevM").onclick = function(){ date.setMonth(date.getMonth() - 1); time(); } document.getElementById("nextM").onclick = function(){ date.setMonth(date.getMonth() + 1); time(); } } </script>