如何使用CSS寫一個簡易的日歷呢?下面我們來介紹一下:
/* HTML代碼 */ <div id="calendar"> <div class="header"> <span class="prev"></span> <span class="month"></span> <span class="next"></span> </div> <div class="weekdays"> <div>Su</div> <div>Mo</div> <div>Tu</div> <div>We</div> <div>Th</div> <div>Fr</div> <div>Sa</div> </div> <div class="days"> <div class="day"></div> ... <div class="day"></div> </div> </div> /* CSS代碼 */ #calendar { background-color: #fff; box-shadow: 0 0 20px rgba(0, 0, 0, .1); width: 300px; } .header { background-color: #1451a1; color: #fff; display: flex; justify-content: space-between; align-items: center; height: 50px; padding: 0 10px; } .weekdays { display: flex; justify-content: space-around; align-items: center; height: 30px; background-color: #f0f0f0; font-weight: bold; } .days { display: flex; flex-wrap: wrap; padding: 10px; } .day { width: calc(100% / 7); height: 40px; display: flex; justify-content: center; align-items: center; } /* JavaScript代碼 */ const calendar = document.getElementById('calendar'); const prevBtn = calendar.querySelector('.prev'); const nextBtn = calendar.querySelector('.next'); const monthField = calendar.querySelector('.month'); const dayFields = calendar.querySelectorAll('.day'); let currMonth = new Date().getMonth(); let currYear = new Date().getFullYear(); prevBtn.addEventListener('click', () =>{ if (currMonth === 0) { currMonth = 11; currYear--; } else { currMonth--; } updateCalendar(); }); nextBtn.addEventListener('click', () =>{ if (currMonth === 11) { currMonth = 0; currYear++; } else { currMonth++; } updateCalendar(); }); function updateCalendar() { const daysInMonth = new Date(currYear, currMonth + 1, 0).getDate(); const startDay = new Date(currYear, currMonth, 1).getDay(); const endDay = new Date(currYear, currMonth, daysInMonth).getDay(); monthField.textContent = new Date(currYear, currMonth).toLocaleString('default', { month: 'long', year: 'numeric' }); dayFields.forEach((field, index) =>{ const day = index - startDay + 1; if (index< startDay || index >daysInMonth + startDay - 1) { field.textContent = ''; } else { field.textContent = day; if (currMonth === new Date().getMonth() && currYear === new Date().getFullYear() && day === new Date().getDate()) { field.classList.add('today'); } else { field.classList.remove('today'); } } }); } updateCalendar();
以上是簡單的日歷實現代碼,請參考以上示例進行自己的實踐。在這里,我們使用了HTML、CSS和JavaScript三種技術進行了實現。