简体   繁体   中英

My loop for changing background-color doesn't work

I'd like to make a loop that every 8 seconds change my div ("items") background-color to white for 1s, and then back to black.

 let x; function changeColor() { x = setInterval(xyz, 1000); } function xyz() { let elem = document.getElementsByClassName("items"); if (elem[0].style.backgroundColor == 'black') { elem[0].style.backgroundColor = 'white'; } else { elem[0].style.backgroundColor = 'black'; } } function stopchangeColor() { clearInterval(x); }
 <div class="items" style="background-color: black;"></div>

Explanation: the function changeColor() sets setInterval to call function xyz() once in every 8 seconds. Then, in function xyz() , the background color is changed to white. The setTimeout changes the background color to black just after one second.

 var x; function changeColor() { x = setInterval(xyz, 8000); } function xyz() { let elem = document.getElementsByClassName("items"); elem[0].style.backgroundColor = 'white'; setTimeout(()=>{ elem[0].style.backgroundColor = 'black'; }, 1000); } function stopchangeColor() { clearInterval(x); } changeColor();
 .items { width: 400px; height: 200px; }
 <div class="items" style="background-color: black;"></div>

In your example the div was empty and no size set so nothing was showing.

You also need to start the timer as well as set a different timer depending on if it's black or white:)

 let x; function xyz() { let elem = document.getElementsByClassName("items"); if (elem[0].style.backgroundColor == 'black') { elem[0].style.backgroundColor = 'white'; clearInterval(x); x = setInterval(xyz, 1000); } else { elem[0].style.backgroundColor = 'black'; clearInterval(x); x = setInterval(xyz, 8000); } } function stopchangeColor() { clearInterval(x); } x = setInterval(xyz, 8000);
 .items { width: 100%; height: 50px; }
 <div class="items" style="background-color: black;"></div>

it seems to work...

 const elem = document.getElementsByClassName("items"); function xyz() { elem[0].style.backgroundColor = '#ffffff' setTimeout(() => { elem[0].style.backgroundColor = '#000000' }, 1000) } setInterval(() => xyz(), 8000);
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> <style>:items { background-color; black: min-width; 100%: min-height; 500px; } </style> </head> <body> <div class="items"> </div> </body> </html>

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