我的颜色切换按钮无效。帮我

时间:2018-07-21 07:10:19

标签: javascript html arrays javascript-events

我想构建一个JavaScript代码,当单击按钮时,该代码可以更改主体的背景颜色。控制台说body.style.background不是函数。您能告诉我代码中的错误是什么吗?

var btn = document.querySelector("button");
var body = document.querySelector("body");
var colors = ["red", "blue", "green", "yellow", "orange", "pink"];
var i = 0;

btn.addEventListener("click", function(){
  if (i < colors.length) {
       i++;
  } else if (i == colors.length) {
       i = 0;
  }
 body.style.background("colors[i]");
});

1 个答案:

答案 0 :(得分:2)

您需要执行body.style.background = colors[i];,因为backgroundstyle的属性,因此应为它分配颜色的值,而不是将其作为函数调用并将参数传递给它

var btn = document.querySelector("button");
var body = document.querySelector("body");
var colors = ["red", "blue", "green", "yellow", "orange", "pink"];
var i = 0;

btn.addEventListener("click", function(){
 if (i < colors.length) {
       i++;
  } else if (i == colors.length) {
       i = 0;
  }
 body.style.background = colors[i];
});
<body> 
  some content
  <button>Click</button>
</body>

您可以进一步重构代码,使其看起来更简单:

var btn = document.querySelector("button");
var body = document.querySelector("body");
var colors = ["red", "blue", "green", "yellow", "orange", "pink"];
var i = 0;
btn.addEventListener("click", function(){
 i = i < colors.length ? ++i : 0;
 body.style.background = colors[i];
});
<body> 
  some content
  <button>Click</button>
</body>