css JavaScript在单击时更改和保存背景

x33g5p2x  于 2023-06-25  发布在  Java
关注(0)|答案(1)|浏览(84)

我需要改变页面的背景使用与onlick功能,但它没有改变任何东西,既没有保存到localStorage。以下是我目前所拥有的
HTML

<div class="colors" onclick="setBackground('#ECF3F9')">Elegant</div>

<div class="colors" onclick="setBackground('#F1F9EC')">Modern</div>

<div class="colors" onclick="setBackground('#F2EBDD')">Classic</div>

<div class="colors" onclick="setBackground('#121212')">Dark</div>

CSS

.colors {display:inline-block;width:50px;height:30px;border:1px solid black;margin:10px;}

简单的JavaScript

function setBackground(color) 
{
localStorage.setItem("name", color);

}
if(localStorage.name)   //Accessing name variable of localStorage.
{
document.body.style.background = localStorage.name;
}

我还创建了一个Codepen来查看它的实际操作https://codepen.io/familias/pen/BaGLeBj
你知道为什么它不保存点击更改吗?

2wnc66cl

2wnc66cl1#

你忘了改变页面的背景颜色。
下面的代码不能在Stack Overflow中工作,因为它是沙盒的,但它可以在SO之外工作。

// Don't use inline event attributes like onXyz. 
// Separate your JavaScript from your HTML and set up events
// the modern way.
document.querySelector(".wrapper").addEventListener("click", function(event) {
  setBackground(event, event.target.classList[0]);
});

if(localStorage.name) {
  // Accessing name variable of localStorage
  document.body.classList.add(localStorage.name);
}

function setBackground(event, color) {
  if(event.target.classList.contains("colors")){
    document.body.className = "";
    document.body.classList.add(color);
    localStorage.setItem("name", color);
  }
}
.colors {
  display:inline-block;
  width:125px;
  height:40px;
  border:1px solid black;
  margin:10px;
  padding:5px;
  text-align:center;
  cursor:pointer;
}
  
/* Don't use inline styles (the style property).
   Instead add/remove classes.  */
.elegant { background:#ECF3F9; }
.modern { background:#F1F9EC; }
.classic { background:#F2EBDD; }
.dark { background:#121212; color:#fff; }
<div class="wrapper">
  <div class="elegant colors">Elegant</div>
  <div class="modern colors">Modern</div>
  <div class="classic colors">Classic</div>
  <div class="dark colors">Turn off the lights</div>
</div>

相关问题