js实现日历颜色
实现日历颜色标记的方法
使用HTML和CSS基础结构
创建一个基础的日历HTML结构,通常使用表格(<table>)来布局日历的日期格子。每个日期格子(<td>)可以添加自定义的类或数据属性来标记颜色。
<table id="calendar">
<thead>
<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>
</thead>
<tbody>
<tr>
<td data-date="2023-10-01">1</td>
<td data-date="2023-10-02">2</td>
<!-- 其他日期格子 -->
</tr>
</tbody>
</table>
动态生成日历并标记颜色
通过JavaScript动态生成日历,并根据条件(如事件、状态)为日期格子添加颜色类。
function generateCalendar(year, month) {
const daysInMonth = new Date(year, month + 1, 0).getDate();
const firstDay = new Date(year, month, 1).getDay();
const calendarBody = document.querySelector('#calendar tbody');
calendarBody.innerHTML = '';
let date = 1;
for (let i = 0; i < 6; i++) {
const row = document.createElement('tr');
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
row.appendChild(document.createElement('td'));
} else if (date > daysInMonth) {
break;
} else {
const cell = document.createElement('td');
cell.textContent = date;
cell.setAttribute('data-date', `${year}-${month + 1}-${date}`);
// 标记颜色示例:偶数日为红色,奇数日为蓝色
if (date % 2 === 0) {
cell.classList.add('red-day');
} else {
cell.classList.add('blue-day');
}
row.appendChild(cell);
date++;
}
}
calendarBody.appendChild(row);
}
}
generateCalendar(2023, 9); // 生成2023年10月的日历
通过CSS定义颜色样式
为不同的颜色标记定义CSS类,例如:
.red-day {
background-color: #ffcccc;
color: #ff0000;
}
.blue-day {
background-color: #ccccff;
color: #0000ff;
}
.event-day {
background-color: #ccffcc;
border: 2px solid #00aa00;
}
根据事件数据动态标记颜色
从后端或本地数据获取事件信息,动态为日期格子添加颜色标记。
const events = {
'2023-10-05': { color: 'event-day', title: 'Meeting' },
'2023-10-12': { color: 'event-day', title: 'Birthday' }
};
function markEventDays() {
document.querySelectorAll('#calendar td[data-date]').forEach(cell => {
const date = cell.getAttribute('data-date');
if (events[date]) {
cell.classList.add(events[date].color);
cell.setAttribute('title', events[date].title);
}
});
}
markEventDays();
使用第三方库简化实现
如果需要更复杂的日历功能,可以使用第三方库如FullCalendar、Day.js等。以下是FullCalendar的简单示例:

document.addEventListener('DOMContentLoaded', function() {
const calendarEl = document.getElementById('calendar');
const calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
events: [
{ title: 'Event 1', start: '2023-10-05', color: '#ff0000' },
{ title: 'Event 2', start: '2023-10-12', color: '#00aa00' }
]
});
calendar.render();
});






