简体   繁体   English

我应该将 localStorage 放在这段代码中的什么位置?

[英]Where should I put the localStorage in this code?

I am trying to make the dark/light mode theme on my site store locally so that it doesnt untoggle every time a new page is opened or the site is refreshed.我正在尝试在本地存储我的站点上的暗/亮模式主题,以便每次打开新页面或刷新站点时它都不会切换。 Where should I put the localStorage.我应该把localStorage. ? ? Or is the whole thing wrong?还是整个事情都错了?

const checkbox = document.getElementById('checkbox');
        
        checkbox.addEventListener('change',()=> {
          // change theme of website
          document.body.classList.toggle('dark');
        });

You can use localStorage for this, which allows you to access the Storage object.您可以为此使用localStorage ,它允许您访问Storage object。 This is similiar to a session, the difference is that localStorage will not expire and also will not be lost on page refresh.这类似于 session,不同的是localStorage不会过期,也不会在页面刷新时丢失。

Here is a sample use:这是一个示例使用:

 localStorage.setItem('key', 'value'); console.log(localStorage.getItem('key')) // logs 'value' // This snippet can fail as this is only a sandbox, but should work on any regular browser.

Reference: https://developer.mozilla.org/pt-BR/docs/Web/API/Window/localStorage参考: https://developer.mozilla.org/pt-BR/docs/Web/API/Window/localStorage

if you're using vanilla javascript ie on you html you've loaded your script as below如果您使用的是香草 javascript 即在您 html 上,您已按如下方式加载脚本

<html>
...

<script src='/to/scripts.js'></script>
</body>
</html>

Then you can add two functions, one which set the them to localStorage and the other which reads it and make it accessible.然后您可以添加两个函数,一个将它们设置为 localStorage,另一个读取它并使其可访问。

on update the update function sets the new value for the theme, on read the read function reads the stored value even after refresh/reloads as below在更新时更新 function 设置主题的新值,在读取时读取 function 即使在刷新/重新加载后也会读取存储的值,如下所示

<html>
  ....
 <script>
  //for setting
   const toggleTheme = () => {
      if(localStorage.getItem('theme') === 'dark'){
         localStorage.setItem('theme','light')
      }else{
          localStorage.setItem('theme','dark')
       }
   }
  //for reading
   const theme = () => localStorage.getItem('theme') || 'light'
 </script>

 <script src='/to/scripts.js'></script>
 </body>
 </html>

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

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