使用JS更改点击时主体的背景颜色



当用户单击页面顶部的按钮(单击此处更改正文背景的颜色(时,我想更改正文的bg;这是页面:https://relaxed-ardinghelli-701d99.netlify.app/我只做过一次;我使用了for循环,所以相同的代码会被执行10或20次。。但它不起作用:

for(let i=0; i<100; i++){
bg_button.addEventListener("click", funct2);
function funct2(e) {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
bg_button.addEventListener("click", funct3);
function funct3(e) {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""}}}

如果你想让按钮切换背景颜色,无论你点击多少次,你都可以在一个更新状态变量的事件监听器中完成:

let toggleState = false
function toggleBackground() {
toggleState = !toggleState
if (toggleState) {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
} else {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""
}
}
bg_button.addEventListener("click", toggleBackground);

或者,您可以替换事件侦听器,而不是在单击时添加新的侦听器:

function setBg1() {
body.style.backgroundColor = "lightgrey"
section_top.style.backgroundColor="white"
bg_button.onclick = setBg2
}
function setBg2() {
body.style.backgroundColor = "white"
section_top.style.backgroundColor=""
bg_button.onclick = setBg1
}
bg_button.onclick = setBg1

如果您想更改按钮点击时的背景颜色,您应该使用JavaScript函数并更改HTML页面中的样式。

function chBackcolor(color) {
document.body.style.background = color;
}

它是JavaScript中用于更改颜色的函数,您将在活动中调用此函数,例如:

<input type="button" onclick="chBackcolor('red');">

如果你只需要几秒钟,你可以使用setTimeout函数:

window.setTimeout("chBackColor()",10000);

你好,可以使用以下函数:

function bgColorToggle () {
const availableColors = ['blue','red'];
for(int i=0;i<100;i++) {
let color = availableColors[i%2];
setTimeout((document.body.style.color = color),2000);
}
}

最新更新