简体   繁体   English

使用for循环动态更改Div颜色

[英]Change Div Color Dynamically using for loop

let colors = ["red","green","cyan"];
let start = colors[0];
let div = document.getElementById("color");


setInterval(function(){
  document.getElementById("color").style.backgroundColor=colors[0];
  for(var x = 0; x < colors.length; x++){
      document.getElementById("color").style.backgroundColor=colors[x];
      if(colors[x] == colors[colors.length-1]){
          div.style.backgroundColor=start;
          colors[x]++;
      }
    }
},500);

Basically, it loops through the colors but it doesn't reset. 基本上,它会遍历颜色,但不会重置。 What am I actually doing wrong here? 我在这里实际上在做什么错?

Update: 更新:

Thanks to the answer below, I was able to understand what I was doing incorrectly. 多亏了以下答案,我才能够了解自己在做错什么。 I've re-written it based on the way I was trying to do it with For Loops. 我已经根据尝试使用For Loops的方式重新编写了它。

let colors = ["red","green","cyan","purple","grey"];
let div = document.getElementById("color");

document.getElementById("color").style.backgroundColor=colors[0];

for(let x = 0; x < (colors.length / colors.length); x++){
    var i = x;
    div.style.backgroundColor=colors[i];
}

setInterval(function(){
    div.style.backgroundColor=colors[i];
    i++;
    if(i==colors.length){
        i=0;
    }
},300);

Although inefficient, this is the way I wanted to do it solely for the purpose of testing purposes. 尽管效率低下,但这是我仅出于测试目的而想要这样做的方式。

You are running the for loop every 500ms ... but each color change is done within the loop immediately 您每500毫秒运行一次for循环...但是每次更改颜色都会立即在循环内完成

There's no time for the browser to show anything else but the last background 除了最后的背景,浏览器没有时间显示其他任何内容

If what you want to do is simply cycle through those colors, the code is very simple 如果您只是想在这些颜色之间循环,那么代码非常简单

 let colors = ["red","green","cyan"]; let index = 0; let div = document.getElementById("color"); setInterval(function(){ div.style.backgroundColor=colors[index]; index = (index + 1) % colors.length; },500); 
 <div id="color"> DIV! </div> 

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

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