【发布时间】:2020-10-25 04:18:05
【问题描述】:
我试图在 javascript 中编写一个改变背景的效果,点击按钮会改变背景颜色。问题是我应该使用一组颜色作为背景颜色。在每次单击时,按钮应使颜色循环通过数组。这是下面的代码:-
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>background-changer</title>
</head>
<body>
<style>
body{
display: flex;
justify-content: center;
align-items: center;
}
button{
color: white;
background-color: black;
font-weight: 400;
font-family: sans-serif;
font-size: 28px;
border: 0;
border-radius: 5px;
padding: 1rem 2rem;
}
button:hover{
background-color: rgba(0, 0, 0, 0.8);
}
</style>
<button onclick="ChangeBackground()">CHANGE COLOR</button>
<script>
const btn = document.querySelector('button');
var backgrounds = ['red', 'royalblue', 'green', 'purple', 'yellow'];
function ChangeBackground(){
backgrounds.forEach(strtChng);
}
function strtChng(){
let i=0;
if(i<=backgrounds.length){
i++;
document.body.style.backgroundColor = backgrounds[i];
console.log(backgrounds[i]);
}
else{
i=0;
}
}
</script>
</body>
</html>
【问题讨论】:
-
点击一次时,控制台还会显示 ROYALBLUE 循环 5 次。
-
"not working" 不是有用的错误/问题描述。发生什么了?相反应该发生什么?控制台有错误吗?
-
“
<style>元素必须包含在文档的<head>中。” (MDN) -
backgrounds.forEach(strtChng)没有意义 -
您想每次点击更改一次颜色吗?
标签: javascript html dom background-color