背景颜色不变

时间:2019-08-24 18:57:26

标签: javascript arrays loops for-loop

这是我的代码,当我单击按钮(btnColor)时,它仅显示数组中的最后一种颜色,并且不起作用

var color = ["#222F3E","#F368E0","#EE5253","#ABDE3","#10AC84","#222F3E","#5F27CD","pink"];
var btnColor = document.getElementById("color_change");


btnColor.addEventListener("click", function() {

    for(var i = 0; i < color.length; i++) {
        document.querySelector("body").style.background = color[i];
    }
})

2 个答案:

答案 0 :(得分:1)

它会循环显示所有颜色,但是当您按下按钮时会立即发生。

要澄清:它会循环遍历所有内容,但是发生得太快了,您看不到。

如果要在按下按钮时使背景循环一次,请使用以下代码。

var color = ["#222F3E","#F368E0","#EE5253","#ABDE3","#10AC84","#222F3E","#5F27CD","pink"];
var btnColor = document.getElementById("color_change");
var colorI = 0;

btnColor.addEventListener("click", function() {

    document.querySelector("body").style.background = color[colorI];
    colorI++;
    colorI = colorI % color.length;
})

答案 1 :(得分:0)

代替循环,添加变量colorIndex并在每次单击按钮后将其递增,然后检查是否到达末尾,将其重置为0

var color = ["#222F3E", "#F368E0", "#EE5253", "#ABDE3", "#10AC84", "#222F3E", "#5F27CD", "pink"];
var btnColor = document.getElementById("color_change");

var colorIndex = 0;

btnColor.addEventListener("click", function() {
  if (colorIndex === color.length) colorIndex = 0;
  document.querySelector("body").style.background = color[colorIndex++];

})
<button id="color_change">Click me</button>