因此,我一直在尝试进行此切换,这很简单。声明变量“ num”开头等于1,并在“ num”等于2时设置“ if”或“ while”语句,某个div的背景颜色将从白色变为黄色,然后以.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:25 pm非常感谢帮助的人!我的一个朋友实际上给了我一些建议,那就是使用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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句