我正在尝试循环访问保存我的颜色的数组。当用户单击“下一步”按钮时,程序应按顺序显示新颜色。我似乎就是不能让它工作,无论我怎么尝试。我知道这很愚蠢,但我对JavaScript很陌生。
var colors = ["red", "green", "blue", "purple", "yellow"]; /*Array to hold our colors*/
var i; /*iterative variable*/
var colorsLength = colors.length;
function iterate() {
  for (i of colors) {
    if((i<colorsLength) || (document.getElementById("forward").clicked = true)) {
      i++;
      document.getElementById("banner").style.backgroundColor = colors[i];
    }else{
      i = 0;
      document.getElementById("banner").style.backgroundColor = colors[i];
    }
  }
}html, body{
  height           : 100%;
  }
#banner {
  background-color : blue;
  padding-top      : 5%;
  padding-left     : 10%;
  height           : 30%;
  }
#buttons {
  margin-top       : 1em;
  padding-left     : 1em;
  }<div id="banner">
  <h1> This is only the beginning... </h1>
</div>
<div id="buttons">
  <input id = "back"    type="button" value="previous" onclick="iterate()"/>
  <input id = "forward" type="button" value="next"     onclick="iterate(); return true;"/>
</div>
任何帮助都将不胜感激。
发布于 2021-03-16 21:57:13
这个怎么样?
<div id="back" style="width: 100px; height: 100px;">
    <h1>color changes</h1>
</div>
<button onclick="move(-1)">prev</button>
<button onclick="move(1)">next</button>在javascript中
let colors = ["red", "green", "blue", "purple", "yellow"];
let current = 0;
let back = document.getElementById("back")
back.style.backgroundColor = colors[0]
function move(dir){
  current += dir;
  if(current < 0) current = colors.length - 1;
  if(current === colors.length) current = 0;
  back.style.backgroundColor = colors[current]
}如果超出范围,它会返回到最终颜色或第一颜色。
https://stackoverflow.com/questions/66643119
复制相似问题