You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决sessionStorage控制Cookie Banner页面切换短暂闪现问题

解决Cookie Banner页面导航时短暂闪现的问题

你的Cookie Banner在页面间导航时闪现,核心原因是原代码在window.load事件中才隐藏Banner——这个事件要等页面所有资源加载完成后才触发,而Banner已经在页面初始渲染时显示出来,之后才被JS隐藏,所以会出现短暂的闪现。

下面是修复后的完整代码,同时统一了类控制逻辑,避免样式冲突:

<div id="cookie-banner" class="hidden">
    <p class="banner-text">本博客仅使用运行所需的必要技术Cookie。</p>
    <button id="ok-button">确认</button>
</div>

<style>
    #cookie-banner {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: black;
        color: white;
        text-align: center;
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 25px;
    }

    .banner-text {
        margin: 0;
    }

    #ok-button {
        background-color: green;
        color: white;
        border: none;
        padding: 8px 16px;
        margin-left: 10px;
        cursor: pointer;
        font-size: 25px;
    }

    @media only screen and (max-width: 768px) {
        #cookie-banner {
            font-size: 21px;
            padding-left: 33px;
        }

        #ok-button {
            padding: 8px 16px;
            font-size: 30px;
            white-space: nowrap;
        }
    }
    
    #cookie-banner.hidden {
        display: none;
    }
</style>

<script>
    // 立即检查sessionStorage,DOM解析到此处就执行,避免闪现
    const cookieConsent = sessionStorage.getItem('cookieConsent');
    if (cookieConsent !== 'true') {
        document.getElementById('cookie-banner').classList.remove('hidden');
    }

    // 点击按钮隐藏Banner并设置sessionStorage
    function chiudiBanner() {
        const banner = document.getElementById('cookie-banner');
        banner.classList.add('hidden');
        sessionStorage.setItem('cookieConsent', 'true');
    }

    document.getElementById('ok-button').addEventListener('click', chiudiBanner);
</script>

关键修改说明:

  • 提前执行判断逻辑:移除了window.load监听,直接在Banner元素后执行sessionStorage检查,DOM解析到这里就立即控制Banner的显示状态,从根源避免闪现。
  • 统一样式控制:用#cookie-banner.hidden的优先级选择器(比单独的.hidden优先级高)来控制隐藏,避免行内样式和类的冲突问题。
  • 简化按钮逻辑:点击按钮时直接添加.hidden类,不需要toggle(因为只需要隐藏操作)。

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:15:29