如何使用JS循环遍历数组以更改背景颜色?

Bur*_*sha 1 javascript loops

首先,我知道使用 CSS 实现这一点会更简单,但我真的很想用 JS 进行循环,因为它对我来说是一个新概念

我想要发生的是“bg”类一次循环遍历多种背景颜色

我的代码目前不起作用,非常感谢一些指导:)

HTML

<div class="bg"></div>
Run Code Online (Sandbox Code Playgroud)

CSS

.bg {
   width: 100%;
   height: 100%;
}
Run Code Online (Sandbox Code Playgroud)

JS

var bg = document.getElementByClassName('bg');
var colours = ["#CCCDFF", "#BAC7E8", "#D9EEFF", "#BADFE8"];
  for (i = 0; i < colours.length; i++) {
    setInterval(change, 200); 
    function change() {
      bg.style.background = colours;
    }
  }
Run Code Online (Sandbox Code Playgroud)

Sco*_*cus 5

这条线有3个大问题:

var bg = document.getElementByClassName('bg');
Run Code Online (Sandbox Code Playgroud)
  1. 方法是getElementsByClassName()。你错过了一个“s”。
  2. .getElementsByClassName()返回所有匹配元素的节点列表(集合)。集合没有style属性,只有单个元素会有。您必须首先从集合中提取一个元素,然后访问它的style.
  3. .getElementsByClassName()返回一个“实时”节点列表,这对性能有很大影响。这是一个非常古老的 API,不应在 2019 年使用。

接下来,因为间隔定时器会以指定的间隔连续运行,所以不需要循环。计时器的重复性质就像一个循环。

接下来,在您的 CSS 中,您使用百分比指定元素的大小,但百分比必须与其他内容相关,否则它们将不起作用。如果您希望元素与页面一样大,请使用vwvh(视口宽度和视口高度)。

var bg = document.getElementByClassName('bg');
Run Code Online (Sandbox Code Playgroud)
// Don't use `.getElementsByClassName()`
var bg = document.querySelector('.bg');
var colours = ["#CCCDFF", "#BAC7E8", "#D9EEFF", "#BADFE8"];
var index = 0; // Will keep track of which color to use

function change() {
  // If we have run out of colors, stop the timer
  if(index >= colours.length){ clearInterval(timer); }
  
  // Set the color and increment the index
  bg.style.backgroundColor = colours[index++];
}

// Start the timer but get a reference to it 
// so we can stop it later
var timer = setInterval(change, 200); 
Run Code Online (Sandbox Code Playgroud)
.bg {
   width: 100vw;
   height: 100vh;
}
Run Code Online (Sandbox Code Playgroud)