简体   繁体   English

我更改背景颜色的循环不起作用

[英]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.我想创建一个循环,每 8 秒将我的 div(“项目”)背景颜色更改为白色,持续 1 秒,然后再变回黑色。

 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.说明: function changeColor changeColor()设置setInterval以每 8 秒调用一次 function xyz() Then, in function xyz() , the background color is changed to white.然后,在 function xyz()中,背景颜色变为白色。 The setTimeout changes the background color to black just after one second. setTimeout在一秒钟后将背景颜色更改为黑色。

 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.在您的示例中, div 是空的,并且没有设置大小,因此没有显示任何内容。

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>

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

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