如何使用PHP Cookies存储用户深色模式主题偏好并设置指定有效期
实现方案
1. 修改JavaScript切换逻辑
切换主题时同步将当前状态发送给PHP接口存储Cookie:
function myFunction() { var element = document.body; element.classList.toggle("dark-mode"); // 获取当前主题状态:深色模式为1,浅色为0 const themeStatus = element.classList.contains("dark-mode") ? 1 : 0; // 发送AJAX请求到PHP存储Cookie const xhr = new XMLHttpRequest(); xhr.open("POST", "save_theme.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("theme_status=" + themeStatus); }
2. 编写PHP Cookie存储接口(新建save_theme.php文件)
可自定义Cookie有效期,以下示例设置为保留30天:
<?php // 校验参数是否存在 if (isset($_POST['theme_status'])) { // 过滤参数值,只允许0或1 $themeStatus = intval($_POST['theme_status']) === 1 ? 1 : 0; // Cookie有效期设置:30天 = 30 * 24小时 * 60分钟 * 60秒 $expireTime = time() + 30 * 24 * 60 * 60; // 第四个参数/表示Cookie全站生效 setcookie("user_prefer_theme", $themeStatus, $expireTime, "/"); // 可选返回操作状态 echo json_encode(['code' => 200, 'msg' => '保存成功']); } ?>
注意:
setcookie方法必须在所有页面输出之前调用,所以save_theme.php文件开头不要留空格、HTML标签等多余内容,否则会导致Cookie设置失败。
3. 页面初始化自动加载用户主题偏好
将你的页面文件后缀改为.php,在body标签处读取Cookie自动添加对应样式类:
<body <?php if (isset($_COOKIE['user_prefer_theme']) && $_COOKIE['user_prefer_theme'] == 1) echo 'class="dark-mode"'; ?>> <!-- 原有页面内容 -->
可选优化补充
你当前的CSS只设置了.mainSection的深色样式,如果需要全局背景生效,可以补充以下CSS:
body.dark-mode { background-color: black; color: white; }
内容的提问来源于stack exchange,提问作者rosamaria
相关产品推荐
相关产品推荐

