【问题标题】:Using localstorage to save background使用localstorage保存后台
【发布时间】:2021-12-26 04:10:03
【问题描述】:

我有一个按钮可以改变背景颜色和标题颜色

button id="change" onclick="change()">Change background!</button>                                           

var state = true;



function change(){
         if (state){
        document.body.style.backgroundColor = "red";
        document.getElementById('title').style.color='blue';

         } else {
            document.body.style.backgroundColor = "#005fff";
            document.getElementById('title').style.color='lightgreen';
                  }
        state = !state;
}

我使用状态在一个和第二个选项之间进行选择,如果您有更好的解决方案请告诉我。

我想将设置保存在本地存储中(刷新并退出后我想保留选择的背景)。

【问题讨论】:

    标签: javascript local-storage web-storage


    【解决方案1】:

    你必须用你自己定义的键更新localStorage,在例子中选择bgcolor。

    此外,当加载脚本时,您应该在文档正文上应用 bgcolor,分配您从 localStorage 获得的值。

    如果没有找到值,我将背景设置为白色。这当然是可选的:)

    var state = true;
    
    document.body.style.backgroundColor = localStorage.getItem('bgcolor') || 'white';
    
    function change(){
      if (state){
        document.body.style.backgroundColor = "red";
        document.getElementById('title').style.color='blue';
        localStorage.setItem('bgcolor', 'red');
    
      } else {
        document.body.style.backgroundColor = "#005fff";
        document.getElementById('title').style.color='lightgreen';
        localStorage.setItem('bgcolor', '#005fff');
      }
      state = !state;
    }
    <h1 id="title">Title</h1>
    <button id="change" onclick="change()">Change background!</button>

    【讨论】:

      【解决方案2】:

      您可以像这样将当前颜色存储在本地存储中:

      function change(){
        const colorOption = localStorage.getItem('colorOption');
        if (colorOption === "2"){
          document.body.style.backgroundColor = "red";
          document.getElementById('title').style.color='blue';
          localStorage.setItem('colorOption', '1');
        } else {
          document.body.style.backgroundColor = "#005fff";
          document.getElementById('title').style.color='lightgreen';
          localStorage.setItem('colorOption', '2');
        }
      }
      

      【讨论】:

      • 我在 devtools 中看到 localstorage 正在工作,但是当我刷新背景时,无论之前的情况如何,背景都会更改为默认值
      猜你喜欢
      • 2012-02-01
      • 2014-03-09
      • 2016-08-27
      • 2016-09-08
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      相关资源
      最近更新 更多