[英]How do i set dark mode theme across multiple pages?
I'm trying to implement a dark mode across my website which has 3 different pages.我正在尝试在我的网站上实现一个暗模式,它有 3 个不同的页面。 I made 3 separate javascript files to each page and copied the dark mode code to each one.我为每个页面制作了 3 个单独的 javascript 文件,并将暗模式代码复制到每个页面。 Now I want to save the preference so that the user doesn't have to keep clicking the dark mode feature every single time they go to a different part of the site.现在我想保存首选项,这样用户就不必每次将 go 转到站点的不同部分时都一直单击暗模式功能。 This is what I have that changes it to dark mode.这就是我将其更改为暗模式的功能。 I've seen answers using localStorage but I'm still new to JS so I'm having trouble implementing it.我已经看到使用 localStorage 的答案,但我还是 JS 的新手,所以我在实现它时遇到了麻烦。 Should I have only one javascript file for all 3 pages or keep it separate files?我应该只为所有 3 页提供一个 javascript 文件还是将其保留为单独的文件?
<label class="switch">
<input type="checkbox" id="darkmode">
<span class="slider round"></span>
</label>
let checkbox = document.getElementById("darkmode");
let body = document.getElementById('body')
checkbox.addEventListener( 'change', function() {
if(this.checked) {
body.classList.add('dark')
} else {
body.classList.remove('dark')
}
});
In order to achieve this, you can do the following:为了实现这一点,您可以执行以下操作:
checkbox.addEventListener( 'change', function() {
localStorage.setItem('dark',this.checked);
if(this.checked) {
body.classList.add('dark')
} else {
body.classList.remove('dark')
}
});
if(localStorage.getItem('dark')) {
body.classList.add('dark');
}
A simple trick is to use the window.localstorage() or cookies(), this will help you to make this functionality easily.一个简单的技巧是使用 window.localstorage() 或 cookies(),这将帮助您轻松实现此功能。
For more information, you can see this article MDN Window.localStorage & MDN cookies.Cookie更多信息可以看这篇文章MDN Window.localStorage & MDN cookies.Cookie
Practical example always help us 100%,实际的例子总是100%帮助我们,
This is a better way to do this stuff.这是做这些事情的更好方法。 https:// codepen.io/Md_Tahazzot/pen/xxKLmJa https://codepen.io/Md_Tahazzot/pen/xxKLmJa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.