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

如何配置Cookie实现网站通知栏关闭后后续访问不再显示

通知栏关闭后持久化隐藏实现方案

只需要补充Cookie读写逻辑即可,无需改动原有HTML结构,核心逻辑分两步:页面加载时校验关闭标记、用户关闭时写入持久化标记。

完整实现代码

JS部分(替换原有JS代码即可)

// 基础Cookie操作方法,无需额外引入第三方依赖
function setCookie(cname, cvalue, exdays) {
  const expireDate = new Date();
  expireDate.setTime(expireDate.getTime() + (exdays * 24 * 60 * 60 * 1000));
  document.cookie = `${cname}=${cvalue};expires=${expireDate.toUTCString()};path=/`;
}

function getCookie(cname) {
  const targetKey = `${cname}=`;
  const cookieList = decodeURIComponent(document.cookie).split(';');
  for (let i = 0; i < cookieList.length; i++) {
    const curCookie = cookieList[i].trim();
    if (curCookie.indexOf(targetKey) === 0) {
      return curCookie.substring(targetKey.length, curCookie.length);
    }
  }
  return '';
}

$(document).ready(function(){
  // 页面加载时优先检查关闭标记,已关闭则直接隐藏通知栏
  if (getCookie('site_notice_closed') === '1') {
    $('.m-bar').hide();
    return;
  }

  $('.m-close').click(function(e){
    // 阻止a标签默认跳转,避免点击后页面回到顶部
    e.preventDefault();
    // 保留原有600ms隐藏动画
    $('.m-bar').hide(600);
    // 写入关闭标记Cookie,默认有效期30天,可按需调整天数
    setCookie('site_notice_closed', '1', 30);
  });
});

HTML部分(无需修改,沿用原有代码即可)

<center>
  <div class="m-bar m-red">
    <a class="m-microphone"><i class="material-icons" style="font-size:26px;">mic</i></a>
    <a class="m-content" style="color: white;">Something Text</a>
    <a class="m-close" href="#"><i class="material-icons">close</i></a>
  </div>
</center> <br><br>

可调配置项

  • 通知有效期:setCookie第三个参数为Cookie有效天数,需要通知7天后重新展示就传7,需要长期不展示就传3650(约10年)即可
  • 多通知适配:如果页面有多个独立通知栏,给每个通知栏设置独立的Cookie名称即可分别控制展示状态
  • 作用范围:当前Cookie设置path=/为整站生效,如果只想在特定目录下生效,修改path为对应路径即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 06:09:26