抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >


网站纪念日自动灰屏实现方案

该方法通过配置清明节等纪念日日期,在对应日期自动为网站首页应用 CSS 灰度滤镜。包含移除旧样式、首页检测、纪念日判断等步骤,并兼容 Pjax 页面切换,确保灰屏效果正确显示。

// 纪念日灰屏处理
// 1. 精确计算清明节日期(返回{month: 4, day: 4/5/6})
function getQingmingDate() {
const today = new Date();
const year = today.getFullYear();
const Y = year % 100; // 取年份后两位
const C = year >= 2000 ? 4.81 : 5.59; // 21世纪C=4.81,20世纪C=5.59
const L = Math.floor(Y / 4); // 闰年数(能被4整除的年份)
const qingming = Math.floor(Y * 0.2422 + C) - L;
// 结果修正:若计算值<4,则为4月4日(防止2月/3月错误)
return { month: 4, day: Math.max(4, qingming) };
}
// 2. 配置纪念日(公历日期)
const memorialDays = [
{ month: 12, day: 13 }, // 南京大屠杀纪念日
getQingmingDate(), // 清明节(覆盖不同年份)
{ month: 7, day: 7 }, // 七七事变纪念日
{ month: 9, day: 18 }, // 九一八事变纪念日
{ month: 9, day: 30 }, // 烈士纪念日
];

// 2. 灰屏逻辑核心函数(独立封装,便于多次调用)
function updateMourningMode() {
// 移除现有灰屏样式(避免状态残留)
document.documentElement.classList.remove('mourning-mode');

// 检查是否为首页
const homePaths = ['/', '/index.html', '/index.htm', '/index'];
const isHomePage = homePaths.includes(window.location.pathname);

if (!isHomePage) return; // 非首页直接退出

// 检查是否为纪念日
const today = new Date();
const currentMonth = today.getMonth() + 1; // 月份从0开始,需+1
const currentDay = today.getDate();
const isMemorialDay = memorialDays.some(day =>
day.month === currentMonth && day.day === currentDay
);

// 纪念日且为首页:应用灰屏样式
if (isMemorialDay) {
document.documentElement.classList.add('mourning-mode');
}
}

// 3. 注入灰度样式(仅一次)
const style = document.createElement('style');
style.textContent = `
html.mourning-mode {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
transition: filter 0.5s ease;
}
`;
document.head.appendChild(style);

// 4. 绑定触发时机(初始加载 + Pjax页面切换)
updateMourningMode();
document.addEventListener('pjax:complete', updateMourningMode); // Pjax核心兼容点

推荐阅读
Pjax性能问题的降级处理 Pjax性能问题的降级处理 Mac Code 代码块全屏 Mac Code 代码块全屏 JavaScript 反调试 JavaScript 反调试 使用Gulp对Hexo静态资源进行压缩 使用Gulp对Hexo静态资源进行压缩 Hexo Hexo Open Search Open Search

留言区

Are You A Robot?