简体   繁体   English

循环更改背景颜色与javascript中的开关

[英]Loop changing background color with switch in javascript

So I've been trying to make this switch, it's simple in my head. 因此,我一直在尝试进行此切换,这很简单。 stating a variable "num" equaling 1 to begin with, setting an "if" or "while" statement for when "num" is equal to 2, the background color of a certain div will change from white to yellow and back in .5 second intervals. 声明变量“ num”开头等于1,并在“ num”等于2时设置“ if”或“ while”语句,某个div的背景颜色将从白色变为黄色,然后以.5返回第二间隔。 My problem I THINK is that I can't seem to change the global variable. 我想的问题是,我似乎无法更改全局变量。 I've changed it to 2, and the loop worked, but when it's 1 and I try to use the button to change to 2, nothing happnes! 我将其更改为2,并且循环正常工作,但是当它为1时,我尝试使用该按钮更改为2,则没有任何反应! Here's the JS I have so far: 这是我到目前为止拥有的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;}

edit: 1/30/2018 12:25pm Really appreciate the help guys! 编辑:1/30/2018 12:25 pm非常感谢帮助的人! A friend of mine actually gave me some advice, that was using window.onload and event timers! 我的一个朋友实际上给了我一些建议,那就是使用window.onload和事件计时器! Here's what I came up with: 这是我想出的:

   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";
    }
}

Instead of setInterval, you can use the timer function directly inside click handler, and your timer function like, 您可以直接在点击处理程序内部使用timer函数,而不是setInterval,您的timer函数就像

var colorChanger = document.getElementById("colorChanger");
function white() {
  colorChanger.style.backgroundColor = "white";
}

function timer(n) {
  num = n;
  if (num == 2) {
    colorChanger.style.backgroundColor = "yellow";
    setTimeout(white, 500);
    return;
  }
  colorChanger.style.backgroundColor = "white";
}

try this, 尝试这个,


 var num = 1; var colorChanger = document.getElementById("colorChanger"); function white() { colorChanger.style.backgroundColor = "white"; } function timer(n) { num = n; if (num == 2) { colorChanger.style.backgroundColor = "yellow"; setTimeout(white, 500); return; } colorChanger.style.backgroundColor = "white"; } document.getElementById("buttonOne").onclick = function() { timer(1); } document.getElementById("buttonTwo").onclick = function() { timer(2); } 
 <div id="colorChanger">switch</div> <button id='buttonOne'>1</button> <button id='buttonTwo'>2</button> 

but when it's 1 and I try to use the button to change to 2, nothing happnes! 但是当它为1时,我尝试使用该按钮将其更改为2,则没有任何反应!

Because, on click, you are changing a variable. 因为在单击时,您正在更改变量。 This will not trigger anything unless it is observable. 除非可以观察到,否则不会触发任何东西。 You will have to wrap related code a function and call it instead. 您将必须将相关代码包装为一个函数,然后调用它。

 function timer(n) { function updateBackground(color) { document.getElementById("colorChanger").style.backgroundColor = "yellow"; } var colors = ['white', 'yellow']; updateBackground(colors[n - 1]); if (n === 2) { setTimeout(function() { updateBackground('white') }, 500); } } document.getElementById("buttonOne").onclick = function() { timer(1); } document.getElementById("buttonTwo").onclick = function() { timer(2); } 
 <div id="colorChanger">switch</div> <button id='buttonOne'>1</button> <button id='buttonTwo'>2</button> 

Few improvements, 很少有改进,

  • Any variable that is not in a function becomes a part of global scope. 任何不在函数中的变量都将成为全局范围的一部分。 You should avoid it. 你应该避免它。
  • I would suggest avoiding .onclick . 我建议避免使用.onclick If I fetch the element and replace it with my function, it will break your code. 如果我获取该元素并将其替换为函数,它将破坏您的代码。 Always prefer using .addEventListener . 始终喜欢使用.addEventListener This is opinionated though. 虽然这是自以为是的。
  • You should use classes instead of setting individual style. 您应该使用类而不是设置单独的样式。 It keeps code clean and maintainable. 它保持代码的清洁和可维护。

 function timer(n) { if (n === 2) { document.getElementById("colorChanger").classList.add("yellow"); setTimeout(function() { document.getElementById("colorChanger").classList.remove("yellow"); }, 500); } } document.getElementById("buttonOne").onclick = function() { timer(1); } document.getElementById("buttonTwo").onclick = function() { timer(2); } 
 .white { background: white; } .yellow { background: yellow; /* This is for demo purpose only */ font-weight: bold; } 
 <div id="colorChanger" class='white'>switch</div> <button id='buttonOne'>1</button> <button id='buttonTwo'>2</button> 

References: 参考文献:

I changed something: 我改变了一些东西:

 (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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM