我正在尝试使用JS事件监听器更改主体的背景颜色。单击该按钮时,没有错误代码,并且颜色没有更改。
//Change body background-color
var buttonFour = document.querySelector("#button-four");
let colorOptions = ["brown", "blue", "orange", "green", "white"];
buttonFour.addEventListener("toggle", function() {
for(let i = 0; i < colorOptions.length; i++) {
document.body.style.background = colorOptions[i];
}
})
答案 0 :(得分:1)
您可能想听的是一个“单击”事件。当<detail>
标签的状态更改时,将特别触发“切换”。 https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement/toggle_event
buttonFour.addEventListener("click", function() {
for(let i = 0; i < colorOptions.length; i++) {
document.body.style.background = colorOptions[i];
}
})
编辑:刚刚意识到,您的处理程序也有问题-每次调用上述处理程序时,背景都会简单地瞬间循环显示所有颜色-始终以白色结尾。您需要跟踪当前显示的颜色,并在每次单击时转到下一个颜色:
function colorChanger() {
let currentColor = 0;
return function handler() {
currentColor = (currentColor + 1) % colorOptions.length
document.body.style.background = colorOptions[currentColor];
}
}
buttonFour.addEventListener("click", colorChanger())
答案 1 :(得分:0)
一些观察结果:
toggle
事件,而不是监听click
事件。解决方案:代替循环,我们可以从数组中获取随机颜色。
//Change body background-color
var buttonFour = document.querySelector("#button-four");
let colorOptions = ["brown", "blue", "orange", "green", "white"];
buttonFour.addEventListener("click", function() {
document.body.style.background = colorOptions[Math.floor(Math.random()*colorOptions.length)];
})
<button id="button-four">Change color</button>
OR
//Change body background-color
var buttonFour = document.querySelector("#button-four");
let colorOptions = ["brown", "blue", "orange", "green", "white"];
buttonFour.addEventListener("click", function() {
for(let i = 0; i < colorOptions.length; i++) {
document.body.style.background = colorOptions[i];
}
const poppedColor = colorOptions.pop();
colorOptions.unshift(poppedColor);
})
<button id="button-four">Change color</button>