如何在按钮单击时永久更改颜色

时间:2021-05-06 16:05:32

标签: javascript html css

我有一个功能,可以在单击按钮时更改框的颜色,而且效果很好。我的问题是当我重新加载页面时,CSS 将恢复为原始框颜色。有没有办法使更改后的盒子颜色永久化。即使重新加载页面,更改后的颜色也不会恢复。不能使用本地存储和 cookie,因为它们不在设备之间共享。类似于在函数 BearerTokenAuthenticationFilter 运行时更改整个代码库。这可能吗。任何帮助表示赞赏。提前致谢。

changeColor
function changeColor() {
  document.getElementById("box1").style.backgroundColor = "green";
}
#box1 {
  width: 150px;
  height: 150px;
  background-color: red;
  position: absolute;
  top: 0px;
  left: 0px;
}

.button1 {
  position: absolute;
  top: 10px;
  left: 200px;
}

3 个答案:

答案 0 :(得分:1)

使用这个功能

1.用键backgroundColor存储颜色值

localStorage.setItem("backgroundColor","red");

2.从本地存储访问

localStorage.getItem("backgroundColor");

3.清除本地存储(需要时可选)

localStorage.clear();

现在您可以从本地存储访问颜色。

答案 1 :(得分:1)

在您的本地机器上试试这个。

function changeColor() {
  document.cookie = "green";
  document.getElementById("box1").style.backgroundColor = "green";
}

function getColor() {
  document.getElementById("box1").style.backgroundColor = document.cookie || "red";
}
#box1 {
  width: 150px;
  height: 150px;
  background-color: red;
  position: absolute;
  top: 0px;
  left: 0px;
}

.button1 {
  position: absolute;
  top: 10px;
  left: 200px;
}
<div id="box1" onload="getColor()"></div>
<button class="button1" onclick="changeColor()">Change color</button>

答案 2 :(得分:0)

那么我认为您必须将更改后的颜色保存到浏览器 cookie 或 localstorage 中。当您加载页面时,从 cookie/localstorage 中获取颜色。如果没有保存颜色,则使用默认颜色渲染 div。

这是一个伪代码。

function changeColor() {
  // save the color in localstorage or cookie
  document.getElementById("box1").style.backgroundColor = "green";
}
function onLoad() {
  // const desiredColor = (read color from localstorage or cookie) || "red";
  document.getElementById("box1").style.backgroundColor = desiredColor;
}
相关问题