当我点击某个框颜色时,我用JavaScript编写的代码应该在区域设置存储中返回他的值,但它只返回我选择的第一个颜色



html代码

css代码

JavaScript代码

代码结果

  1. HTML文件的第9行中有随机标记
  2. 本地存储不适合在开发人员工具中更新实时数据。每次单击listener fires.line 11时,我删除了div标记并添加了console.log(window.localStorage(

let list = document.querySelectorAll("ul li");
let myBox = document.querySelector(".box");
list.forEach((li) => {
li.addEventListener("click", (e) => {
list.forEach((li) => {
li.classList.remove("active");
});
e.currentTarget.classList.add("active");
window.localStorage.setItem("color", e.currentTarget.dataset.color);
console.log(window.localStorage);
});
});
body {
background-color: #333;
}  
ul {
background-color: rgb(207, 204, 204);
width: auto;
height: auto;
display: flex;
justify-content: center;
align-items: center;
}
li {
width: 100px;
height: 100px;
margin-left: 10px;
list-style:  none;
cursor: pointer;
opacity: 0.5;
}
ul li[data-color = "red"] { background-color: red; }
ul li[data-color = "green"] { background-color: rgb(26,131,5); }
ul li[data-color = "blue"] { background-color: rgb(22,8,221) }
ul li[data-color = "black"] { background-color: rgb(20,16,16); }
.box {
height: 400px;
width: 400px;
background-color: blue;
margin: 0 auto;
margin-top: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/styles.css">
<script src="/script.js" defer></script>
</head>
<body>
<ul>
<li class="active" data-color = "red"></li>
<li data-color = "blue"></li>
<li data-color = "green"></li>
<li data-color = "black"></li>
</ul>
<div class="box"></div>
</body>
</html>

最新更新