如何通过 cookie 为暗模式设置用户偏好?

How to set user preference via cookies for dark mode?

在我的 Blogger 博客上,我正在尝试创建一个暗模式亮模式切换器。我已成功创建切换器,但现在我想保存用户首选项,以便如果用户离开暗模式,he/she 将进入暗模式,而 he/she 仅在返回后才会进入暗模式。

这是我到目前为止编写的代码。我需要有关本地存储/cookie 的帮助以保存用户偏好。

<b:tag aria-label='Dark Mode' class='darkmode-toggle' id='modetog' name='a' onclick='myFunction()'><i class='fas fa-adjust'/></b:tag>
<script>
    /* Dark Mode */
var clicks = 0;
$(&#39;#modetog&#39;).click(function() {
if (clicks % 2 === 0){    
document.querySelector(&#39;body&#39;).classList.add(&#39;isdark&#39;);
} else{  
document.querySelector(&#39;body&#39;).classList.remove(&#39;isdark&#39;);
}++clicks;
});
</script>

P.S.: 我还在学习JavaScript,抱歉问了些愚蠢的问题。上网查了也没明白

您可以使用localStorage api (reference):

// Code to save setting
localStorage.setItem('darkTheme', '1'); // Here you can put any string you want, I just chose 2 understandable ones

// Code to retrieve the setting
localStorage.getItem('darkTheme');

编辑:执行此处评论的请求

您可以简单地遍历页面的组件并设置它们的样式以匹配所选主题(尽管加载不同的 css 性能更高并且建议这样做,但这需要编辑大量当前代码)

const theme = localStorage.getItem('darkTheme');

if (theme) {
// Runs only if darkTheme is set to 1, or any truthy value
// (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy for reference)

    document.querySelector('body').classList.add('isdark');
    clicks++; // This is to keep your theme switcher working: if the page starts dark and the user clicks to change the theme you want to revert back to light
}

要将其合并到您的代码中:


/* Dark Mode */
var clicks = 0;

const theme = localStorage.getItem('darkTheme');

if (theme) {
// Runs only if darkTheme is set to 1, or any truthy value
// (see https://developer.mozilla.org/en-US/docs/Glossary/Truthy for reference)

    document.querySelector("body").classList.add("isdark");
    clicks++; // This is to keep your theme switcher working: if the page starts dark and the user clicks to change the theme you want to revert back to light
}

$('#modetog').click(function() {
if (clicks % 2 === 0){    
    document.querySelector('body').classList.add('isdark');
    localStorage.setItem('darkTheme', '1');
} else{  
    document.querySelector('body').classList.remove('isdark');
    localStorage.setItem('darkTheme', '0');
}
++clicks;
});