所以我一直在尝试进行这种转换,在我看来这很简单。首先声明一个变量“num”等于1,设置一个“if”或“while”语句,当“num”等于2时,某个div的背景颜色将从白色变为黄色,然后在0.5中变回白色第二个间隔。我认为我的问题是我似乎无法更改全局变量。我已将其更改为 2,并且循环有效,但是当它为 1 并且我尝试使用按钮更改为 2 时,没有任何反应!这是我到目前为止的 JS:
var num = 1;
document.getElementById("numberDisplay").innerHTML = num;
if (num == 2) {
var flash = setInterval(timer, 1000);
function timer() {
document.getElementById("colorChanger").style.backgroundColor = "yellow";
setTimeout(white, 500);
function white() {
document.getElementById("colorChanger").style.backgroundColor = "white";
}
}
} else {
document.getElementById("colorChanger").style.backgroundColor = "white";
document.getElementById("numberDisplay").innerHTML = num;
}
document.getElementById("buttonOne").onclick=function(){num = 1;}
document.getElementById("buttonTwo").onclick=function(){num = 2;}
编辑:1/30/2018 12:25pm 真的很感谢大家的帮助!我的一个 friend 实际上给了我一些建议,那就是使用 window.onload 和事件计时器!这是我想到的:
var num = 1;
window.onload = function(){
var button1 = document.getElementById("buttonOne")
var button2 = document.getElementById("buttonTwo")
button1.addEventListener("click",function(){
num = 2;
})
button2.addEventListener("click",function(){
num = 1;
})
setInterval(checkNum, 1000);
}
function checkNum() {
if (num == 2) {
document.getElementById("buttonOne").style.backgroundColor = "#ccccb3";
document.getElementById("buttonTwo").style.backgroundColor = "white";
document.getElementById("lightChanger").style.backgroundColor = "yellow";
setTimeout(grey, 500);
function grey() {
document.getElementById("lightChanger").style.backgroundColor = "grey";
}
} else {
document.getElementById("lightChanger").style.backgroundColor = "grey";
document.getElementById("buttonOne").style.backgroundColor = "white";
document.getElementById("buttonTwo").style.backgroundColor = "#ccccb3";
}
}
最佳答案
我改变了一些东西:
(function(){
var changeColor = function(num) {
document.getElementById("numberDisplay").innerHTML = num;
if (num === 2) {
var flash = setInterval(timer, 1000);
function timer() {
document.getElementById("colorChanger").style.backgroundColor = "yellow";
setTimeout(white, 500);
function white() {
document.getElementById("colorChanger").style.backgroundColor = "white";
}
}
} else {
document.getElementById("colorChanger").style.backgroundColor = "white";
document.getElementById("numberDisplay").innerHTML = num;
}
}
document.getElementById("buttonOne").addEventListener('click', function(evt){
let num = 1;
changeColor(num);
});
document.getElementById("buttonTwo").addEventListener('click', function(evt){
let num = 2;
changeColor(num);
});
})();
<div id="numberDisplay"></div>
<div id="colorChanger">Color</div>
<button id="buttonOne">1</button>
<button id="buttonTwo">2</button>
关于javascript - 使用 JavaScript 中的 switch 循环更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48514601/