【发布时间】:2021-09-05 00:32:42
【问题描述】:
我想在每次单击按钮时更改颜色。我使用 forEach 来检查每种颜色。但是在我单击一个按钮后,颜色变为“橙色”,即数组中的最后一种颜色。我的代码中是否缺少某些内容?
window.onload = function() {
const btn = document.querySelector("button");
btn.addEventListener("click", changeColor);
}
function changeColor() {
const colors = ["yellow","green","red","blue","orange"];
colors.forEach(function(color) {
document.body.style.backgroundColor = color;
});
}
body{
background-color:teal;
display: flex;
justify-content: center;
align-items: center;
padding: 180px;
}
button{
background-color: white;
font-size: 30px;
width: 150px;
height: 50px;
border-style: solid;
border-color: black;
border-radius: 10px;
cursor: pointer;
}
<!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">
<link rel="stylesheet" href="/style.css">
<script src="/js.js"></script>
<title>1st project</title>
</head>
<body>
<button class="button">Click me!</button>
</body>
</html>
【问题讨论】:
-
每次点击时,它会将背景设置为数组中的每种颜色,依次以橙色结尾。
-
所以在这种情况下我不能使用 forEach() 方法
-
正确,你想要达到的效果。
标签: javascript foreach background-color