简体   繁体   English

切换到深色模式按钮

[英]Switch to dark mode button

I have a template that sets dark mode only adding a class to the body.我有一个设置暗模式的模板,只向正文添加 class。 This template does not include a toggle button so I am trying to create it by myself but it goes back to light theme when I go to another file or reload the page.此模板不包含切换按钮,因此我尝试自己创建它,但当我将 go 转到另一个文件或重新加载页面时,它会返回浅色主题。

I am using a button and this JS code我正在使用一个按钮和这个 JS 代码

var body = document.querySelector('body');
button.onclick = function(){
body.classList.toggle('dark-layout');
}

The problem is how can I save this settings, because once you reload it turns to the values set by default.问题是我怎样才能保存这个设置,因为一旦你重新加载它就会变成默认设置的值。 I am sure there should be a front-end solution, but the only way I think is to create a table in a db and set the class inside an if and the button will be switching this value我确信应该有一个前端解决方案,但我认为唯一的方法是在数据库中创建一个表并在 if 中设置 class 并且按钮将切换此值

A simplest solution is to use localStorage to store settings.最简单的解决方案是使用localStorage来存储设置。

//read stored setting on startup
let isDarkMode = localStorage.getItem("darkmode");
//apply setting
setDarkMode();

button.onclick = function(){
  isDarkMode = !isDarkMode;
  setDarkMode(isDarkMode);
}
function setDarkMode(value = isDarkMode)
{
  value = ~~value; //convert to integer
  document.body.classList.toggle('dark-layout', value);
  localStorage.setItem("darkmode", value);
}

This cannot be done with front-end as storing data can only be done using databases.这不能用前端来完成,因为存储数据只能使用数据库来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM