当前位置:首页 > JavaScript

JS实现哀悼

2026-01-15 13:54:46JavaScript

实现网页哀悼效果的方法

通过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%);
}

注意事项

  1. 部分现代浏览器可能要求滤镜属性应用于html或body元素才能生效
  2. 使用SVG滤镜时需注意XML特殊字符的转义处理
  3. 某些第三方组件可能不受全局滤镜影响,需要单独处理
  4. 移动端页面建议添加-webkit前缀确保兼容性

JS实现哀悼

标签: JS
分享给朋友:

相关文章

JS实现跳表

JS实现跳表

跳表的基本概念 跳表(Skip List)是一种基于概率的数据结构,允许快速查询、插入和删除操作,时间复杂度平均为O(log n)。它通过多层链表实现,每一层都是下一层的子集,高层链表跳过多个元素,从…