JS实现哀悼
实现网页哀悼效果的方法
通过CSS滤镜和全局样式调整,可以快速实现网页整体变灰的哀悼效果。以下是具体实现方式:

document.addEventListener('DOMContentLoaded', function() {
const style = document.createElement('style');
style.innerHTML = `
html {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
}
`;
document.head.appendChild(style);
});
兼容性处理方案
对于需要支持IE浏览器的场景,可以使用SVG滤镜实现更广泛的兼容性:

const grayscaleStyle = document.createElement('style');
grayscaleStyle.innerHTML = `
html {
filter: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'><filter id='grayscale'><feColorMatrix type='matrix' values='0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0'/></filter></svg>#grayscale");
}
`;
document.head.appendChild(grayscaleStyle);
动态控制哀悼模式
添加控制开关,允许动态启用或禁用哀悼效果:
function setMourningMode(enable) {
const html = document.documentElement;
if (enable) {
html.style.filter = 'grayscale(100%)';
html.style.webkitFilter = 'grayscale(100%)';
} else {
html.style.filter = '';
html.style.webkitFilter = '';
}
}
// 使用示例
setMourningMode(true); // 启用哀悼模式
性能优化方案
对于大型网站,推荐使用CSS类名控制的方式,避免直接操作样式:
function toggleMourningMode() {
document.documentElement.classList.toggle('mourning-mode');
}
// 对应CSS
.mourning-mode {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
}
注意事项
- 部分现代浏览器可能要求滤镜属性应用于html或body元素才能生效
- 使用SVG滤镜时需注意XML特殊字符的转义处理
- 某些第三方组件可能不受全局滤镜影响,需要单独处理
- 移动端页面建议添加-webkit前缀确保兼容性
