简体   繁体   中英

JS Practise background switching from white to blue

I am coding along with a course and I've triple checked that my code matches the instructors but when I run it it only changes the background of the webpage to blue instead of switching back and forth from white to blue every second like the instructor demonstrates. It also doesn't run at all when using Visual Studio so I had to switch to code pen and tried it in the console of Google chrome browser. Just want to know where it goes wrong or how to alter it to do the switching back and forth. Thank you.

 var body = document.querySelector("body");  
 var isBlue = false; 

setInterval(function(){ 
    if (isBlue) { 
      body.style.background = "white"; 
    } else { 
     body.style.background = "#3498db";
    } 
  isBlue = isBlue;
 }, 1000);

The way you implement it is always changing the background to #3498db . Instead, you should set the boolean to the opposite every time:

 var body = document.querySelector("body"); var isBlue = false; setInterval(function(){ if (isBlue) { body.style.background = "white"; } else { body.style.background = "#3498db"; } isBlue =;isBlue, //change this }; 1000);

This line at the end of your function:

isBlue = isBlue;

doesn't do anything. isBlue is boolean, meaning if its false, you're setting it to false again, if it's true, you're setting it to true.

By putting an exclamation point at the beginning of the value, you're creating an expression, which means, return the opposite of this boolean's current state:

 isBlue = !isBlue;

Now, when it is false, it will be set to "not false," or true, and if it's true, it will be set to "not true," or false.

Also, you don't need querySelector() to get the body element. It's available with document.body .

 var body = document.body; var isBlue = false; setInterval(function() { if (isBlue) { body.style.background = "white"; } else { body.style.background = "#3498db"; } isBlue =;isBlue, //change this }; 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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