css 我怎样才能添加颜色,bg永久与本地存储?

ux6nzvsh  于 2023-03-25  发布在  其他
关注(0)|答案(3)|浏览(101)

我的动机是,当用户点击按钮时,按钮的背景颜色和文本颜色将永久改变。当我点击按钮时,颜色会完美地添加,但不是永久的。当我重新加载浏览器页面时,颜色也会被删除。我如何修复它?

index.html:

<body>
    <button class="clickFirst" onclick="click1()">click1</button>
    <input type="color" id="colorID" oninput="changeColor()">
</body>

样式.css:

<style>
    .style1{
      background-color: green;
      color: white;
    }
    .style2{
      background-color: blue;
      color: white;
    }
  </style>

index.js:

function click1(){
    localStorage.setItem("class1","style1");
    green = localStorage.getItem("class1");

    var b1 = document.querySelector(".clickFirst");
    b1.classList.add(green);
}
n3h0vuf2

n3h0vuf21#

您需要从localStorage获取颜色值,并在程序开始时将其设置为元素(button)

n3ipq98p

n3ipq98p2#

你很接近了。更改你的javascript代码,在页面加载时应用颜色
我修改了您的js代码以反映这一点
代码在这里将不起作用,因为stackoverflow不允许访问localStorage,因为它是一个沙箱

function applyColors() {
  green = localStorage.getItem("class1");
  var b1 = document.querySelector(".clickFirst");
  b1.classList.add(green);
}

function storeColor() {
  localStorage.setItem("class1", "style1");
  applyColors();
}

(function () {
  applyColors();
})();
.style1{
      background-color: green;
      color: white;
    }
    .style2{
      background-color: blue;
      color: white;
    }
<button class="clickFirst" onclick="click1()">click1</button>
<input type="color" id="colorID" oninput="changeColor()">
bkhjykvo

bkhjykvo3#

const btn = document.querySelector("button")
const body = document.getElementsByTagName("body")

btn.addEventListener("click", (e) => {
    if (body[0].style.backgroundColor === "white") {
        body[0].style.backgroundColor = "black"
        body[0].style.color = "white"

    } else {
        body[0].style.backgroundColor = "white"
        body[0].style.color = "black"

    }
    localStorage.setItem("bgColor", body[0].style.backgroundColor)
    localStorage.setItem("textColor", body[0].style.color)
})
body[0].style.backgroundColor = localStorage.getItem("bgColor")
body[0].style.color = localStorage.getItem("textColor")

相关问题