Javascript没有从数组中选择背景颜色

Javascript not selecting background color from array

本文关键字:选择 背景 颜色 数组 Javascript      更新时间:2023-09-26

我正在尝试制作一个有几种不同颜色的子标题,就像Ask different页面上的那个。唯一的区别是,我试图让它从Javascript数组中随机选择一种颜色,而不是使用特定的颜色。

我已经定义了我想要使用的十六进制颜色,我面临的问题是它没有在HTML页面中正确显示(根本没有)。有人能教我如何解决这个问题吗?如果可以使用jQuery实现这一点,那么也可以。


以下是我目前所拥有的:

Javascript:

var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'];
onload = changeColor();
function changeColor() {
    subheader.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}

HTML:

<div class="header"></div>
<div class="subheader" id="sub1"></div>
<div class="subheader" id="sub2"></div>
<div class="subheader" id="sub3"></div>
<!-- Repeats till id="sub20" -->

CSS:

.header {
    width:100%;
    height:10%;
    position:absolute;
    background-color:#3399FF;
    left:0;
    top:0;
}
.subheader {
    height:2%;
    width:5%;
    top:10%;
    position:absolute;
}
#sub1 {left:0;}
#sub2 {left:5%;}
#sub3 {left:10%;}
/* Repeats till #sub20 */

FIDDLE


此外,如果有一种方法可以缩短我相当广泛的HTML和CSS,也许可以使用:nth-child()之类的东西,如果你知道怎么做的话,请在你的答案中包括它。谢谢你,任何帮助都将不胜感激。

var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'];
onload = changeColor();

    function changeColor() {
        subheader=document.getElementsByClassName('sub-header');
        for(i=0;i<subheader.length;i++){
        subheader[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        }
    }

演示:https://jsfiddle.net/2asvho0c/4/

JavaScript 有一个小问题

JavaScript

var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'],
    elems = document.getElementsByClassName('sub-header'),
    i;
for (i = 0; i < elems.length; i += 1) {
  var color = color = colors[Math.floor(Math.random() * colors.length)];
  elems[i].style.backgroundColor = color;
}

Fiddle

解释

代码中的错误是您有类型sub-header.style——编译器假设sub-header是一个变量,但它没有定义。我们所做的是添加变量(elems),循环通过它,并应用颜色。另一个问题是变量名不支持-。我希望这对有帮助