如何使用JS循环遍历数组以更改背景颜色? [英] How to loop through an array to change background colours using JS?

查看:32
本文介绍了如何使用JS循环遍历数组以更改背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Firstly, I know it would be more simple to achieve this using CSS but I am really trying to wrap my head around looping with JS as it is a new concept for me

我想发生的是让'bg'类循环遍历多种背景颜色

What I want to happen is for the 'bg' class to loop through a number of background colours once

我的代码当前无法正常运行,请多多关照:)

My code does not currently work would very much appreciate some direction :)

HTML

<div class="bg"></div>

CSS

.bg {
   width: 100%;
   height: 100%;
}

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;
    }
  }

推荐答案

此行存在3个大问题:

var bg = document.getElementByClassName('bg');

  1. 该方法为 getElementsByClassName().您错过了"s".
  2. .getElementsByClassName()返回所有匹配的节点列表(集合)元素.该集合仅具有 style 属性个别元素会.您必须从中提取元素首先集合,然后访问它的style.
  3. .getElementsByClassName()返回活动"节点列表,这很痛苦性能相当好.这是一个很老的API,不应该使用在2019年.
  1. The method is getElementsByClassName(). You missed an "s".
  2. .getElementsByClassName() returns a node list (collection) of all matching elements. The collection doesn't have a style property, only individual elements will. You'd have to extract an element from the collection first and then access it's style.
  3. .getElementsByClassName() returns a "live" node list, which hurts performance quite a bit. It's a very old API and shouldn't be used in 2019.

接下来,由于间隔计时器将以指定的间隔连续运行,因此不需要循环.计时器的重复性起到循环作用.

Next, because the interval timer will run continuously at the specified interval, the loop is not required. The repeating nature of the timer acts as a loop.

接下来,在CSS中,使用百分比指定元素的大小,但是百分比必须相对于其他值,否则它们将不起作用.如果希望元素与页面一样大,请使用 vw vh (视口宽度和视口高度).

Next, in your CSS, you specify your element's size using percents, but percents have to be relative to something else, otherwise they won't work. If you want the element to be as big as the page, use vw and vh (Viewport Width and Viewport Height).

// 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); 

.bg {
   width: 100vw;
   height: 100vh;
}

<div class="bg"></div>

这篇关于如何使用JS循环遍历数组以更改背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆