gpt4 book ai didi

javascript - 如何在不同按钮之间交替颜色?

转载 作者:行者123 更新时间:2023-11-28 14:06:48 26 4
gpt4 key购买 nike

我正在制作一个游戏节目,我的目标是每秒在不同按钮上交替显示绿色。这将通过价格显示出很酷的颜色交替。

我尝试使用 if 语句来检查按钮 1 是否为绿色,如果它为绿色,我将删除该颜色并将颜色添加到按钮 2。

function changeColour() {

// Select all the id button
const butn1 = document.querySelector('#one'),
butn2 = document.querySelector('#two'),
butn3 = document.querySelector(`#three `),
butn4 = document.querySelector(`#four `),
butn5 = document.querySelector(`#five `),
butn6 = document.querySelector(`#six `);


if (butn1.style.backgroundColor === "none") {
setInterval(function() {
butn1.style.backgroundColor = "lightgreen";
}, 1000);
}

if (butn1.style.backgroundColor = "lightgreen") {
butn1.style.backgroundColor = "lightgray";
butn2.style.backgroundColor = "lightgreen";
}

if (butn2.style.backgroundColor === "lightgreen") {
setInterval(function() {
butn2.style.backgroundColor = "lightgray";
butn3.style.backgroundColor = "lightgreen";
}, 1000);
}

if (butn3.style.backgroundColor === "lightgreen") {
setInterval(function() {
butn3.style.backgroundColor = "lightgray";
butn4.style.backgroundColor = "lightgreen";
}, 4000);
}

if (butn4.style.backgroundColor === "lightgreen") {
setInterval(function() {
butn4.style.backgroundColor = "lightgray";
butn5.style.backgroundColor = "lightgreen";
}, 1000);
}

if (butn5.style.backgroundColor === "lightgreen") {
setInterval(function() {
butn5.style.backgroundColor = "lightgray";
butn6.style.backgroundColor = "lightgreen";
}, 1000);
}

if (butn6.style.backgroundColor === "lightgreen") {
setInterval(function() {
butn6.style.backgroundColor = "lightgray";
}, 10);
}

}

setInterval(changeColour, 1000);
<button id="one" class="butn color">$1000</button>
<br>
<br>
<button id="two" class="butn">$2000</button>
<br>
<br>
<button id="three" class="butn">$3000</button>
<br>
<br>
<button id="four" class="butn">$4000</button>
<br>
<br>
<button id="five" class="butn">$5000</button>
<br>
<br>
<button id="six" class="butn">$6000</button>
<br>
<br>

最佳答案

设置索引为0,获取所有按钮,在changeColour函数中,查看index是否等于按钮长度。如果是,将其设置为零。同样在将样式应用到当前索引之前,删除所有按钮的背景颜色。

const btns = document.querySelectorAll('button');
let i = 0;

function changeColour() {
if (i == btns.length) i = 0;
btns.forEach((btn) => btn.classList.remove('greenbg'));
btns[i].classList.add('greenbg')
i++;
}

setInterval(changeColour, 1000);
.greenbg {
background-color: green;
}
<button id="one" class="butn color">$1000</button>
<br>
<br>
<button id="two" class="butn">$2000</button>
<br>
<br>
<button id="three" class="butn">$3000</button>
<br>
<br>
<button id="four" class="butn">$4000</button>
<br>
<br>
<button id="five" class="butn">$5000</button>
<br>
<br>
<button id="six" class="butn">$6000</button>
<br>
<br>

关于javascript - 如何在不同按钮之间交替颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57127025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com