js实现日历颜色
实现日历颜色的JavaScript方法
使用JavaScript为日历添加颜色可以通过CSS类或内联样式动态修改元素外观。以下是几种常见方法:
动态添加CSS类 通过条件判断为不同日期添加特定类名,再利用CSS定义颜色样式:
document.querySelectorAll('.calendar-day').forEach(day => {
if (day.dataset.isHoliday === 'true') {
day.classList.add('holiday-color');
}
});
对应CSS:

.holiday-color {
background-color: #ffcccc;
color: #d80000;
}
直接修改内联样式 适用于需要动态计算颜色的场景:
const days = document.querySelectorAll('.calendar-day');
days.forEach(day => {
const eventCount = parseInt(day.dataset.events);
day.style.backgroundColor = eventCount > 0
? `hsl(${Math.min(eventCount * 30, 120)}, 70%, 80%)`
: '';
});
基于日期状态的染色逻辑

function colorizeCalendar() {
const today = new Date();
const currentMonth = today.getMonth();
document.querySelectorAll('.day-cell').forEach(cell => {
const cellDate = new Date(cell.dataset.date);
// 周末染色
if ([0, 6].includes(cellDate.getDay())) {
cell.style.backgroundColor = '#e6f7ff';
}
// 当前月外日期
if (cellDate.getMonth() !== currentMonth) {
cell.style.opacity = '0.5';
}
});
}
完整日历染色示例
以下是一个结合日期类型的完整实现方案:
const calendar = document.getElementById('calendar');
const events = {
'2023-11-15': { type: 'meeting', color: '#ffeb3b' },
'2023-11-20': { type: 'deadline', color: '#f44336' }
};
function renderCalendar() {
// 生成日历DOM结构后执行染色
[...calendar.querySelectorAll('[data-date]')].forEach(day => {
const dateStr = day.dataset.date;
const event = events[dateStr];
// 事件日期染色
if (event) {
day.style.backgroundColor = event.color;
day.style.borderLeft = `3px solid ${darkenColor(event.color, 20)}`;
}
// 今日标记
if (dateStr === formatDate(new Date())) {
day.classList.add('today-highlight');
}
});
}
function darkenColor(hex, percent) {
// 颜色加深工具函数
const r = parseInt(hex.slice(1,3), 16);
const g = parseInt(hex.slice(3,5), 16);
const b = parseInt(hex.slice(5,7), 16);
return `#${[r,g,b].map(x =>
Math.round(x * (100 - percent)/100).toString(16).padStart(2, '0')
).join('')}`;
}
第三方库集成方案
使用FullCalendar等库时,可通过eventRender回调实现染色:
document.addEventListener('DOMContentLoaded', function() {
const calendarEl = document.getElementById('calendar');
const calendar = new FullCalendar.Calendar(calendarEl, {
eventRender: function(info) {
if (info.event.extendedProps.priority === 'high') {
info.el.style.backgroundColor = '#ff6b6b';
}
}
});
calendar.render();
});
注意事项
- 颜色对比度需符合WCAG可访问性标准
- 移动端需考虑触摸反馈颜色的变化
- 避免使用过多颜色导致视觉混乱
- 深色模式需提供替代配色方案






