跨页面保存网站主题(例如黑暗模式)



我目前正在构建一个音乐博客,该博客使用以下JavaScript代码来切换暗模式/亮模式按钮:

function swapStylesheet(sheet) {
document.getElementById('swap').setAttribute('href', sheet);
}

我的问题是,每当刷新页面或访问新页面时,网站都会恢复到默认的CSS表,而不是记住所选的主题。我可以通过cookie或本地存储或其他方式让我的网站记住用户上次选择的主题吗?

请告诉我!非常感谢。=]

简短的回答是肯定的。你可以通过Cookie或本地存储保存它,有很多方法可以实现这一点,我只给你提供Cookie的参考,你可以在W3School 上测试它

你现在给出的问题只适用于页面之间,但如果你希望它基于用户帐户保留,那么答案是你需要集中";主题";每个帐户的数据,例如数据库或服务器缓存。

https://www.w3schools.com/js/js_cookies.asp

function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
checkCookie();

最新更新