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

如何用Cookie保存背景透明度状态,实现页面刷新后保留设置

用Cookie保存背景透明度状态,实现页面加载自动恢复

完整修改代码

<div id="bg" style="transition: all 0.2s ease-in-out;" class="bg"></div>
<button class="bg-toggle" id="test-button"></button>
<button class="bg-toggle" style="background-color: red; left: 95%;" id="test-button2"></button>

<script>
// 设置Cookie,默认有效期30天,path=/确保全站可访问
function setCookie(name, value, days = 30) {
  const date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  const expires = "expires=" + date.toUTCString();
  document.cookie = `${name}=${value};${expires};path=/`;
}

// 获取指定名称的Cookie值
function getCookie(name) {
  const nameEQ = `${name}=`;
  const ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

const bg = document.querySelector('#bg');
const testBtn = document.querySelector('#test-button');
const testBtn2 = document.querySelector('#test-button2');

// 页面加载时读取Cookie,恢复之前的状态
const savedState = getCookie('bgOpacityState');
if (savedState === 'hidden') {
  // 背景隐藏的状态
  bg.style.opacity = '0%';
  testBtn.style.opacity = '0%';
  testBtn.style.top = '-10000%';
  testBtn2.style.opacity = '100%';
  testBtn2.style.top = '92%';
} else {
  // 默认/背景显示的状态(包括无Cookie的首次访问)
  bg.style.opacity = '100%';
  testBtn.style.opacity = '100%';
  testBtn.style.top = '92%';
  testBtn2.style.opacity = '0';
  testBtn2.style.top = '-10000%';
}

testBtn.addEventListener('click', () => {
  bg.style.opacity = '0%';
  testBtn.style.opacity = '0%';
  testBtn.style.top = '-10000%';
  testBtn2.style.opacity = '100%';
  testBtn2.style.top = '92%';
  // 点击后保存状态到Cookie
  setCookie('bgOpacityState', 'hidden');
});

testBtn2.addEventListener('click', () => {
  bg.style.opacity = '100%';
  testBtn.style.opacity = '100%';
  testBtn.style.top = '92%';
  testBtn2.style.top = '-10000%';
  testBtn2.style.opacity = '0';
  // 点击后保存状态到Cookie
  setCookie('bgOpacityState', 'visible');
});
</script>

关键说明

  • Cookie操作封装:setCookie和getCookie是简化原生Cookie操作的工具函数,path=/保证Cookie在网站所有页面都能读取,避免跳转页面后状态丢失。
  • 状态持久化:用bgOpacityState这个Cookie键存储状态,值为visible(背景显示)或hidden(背景隐藏),比直接存透明度值更直观,能同时对应按钮的显示状态。
  • 页面初始化恢复:页面加载时优先读取Cookie值,存在则恢复对应状态,不存在则使用默认的背景显示状态,兼容首次访问的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:42:17