用JS更改不同颜色的主体背景

卡拉什尼科夫:

因此,我是JavaScript的新手,我想创建一个按钮,该按钮在按下时会更改主体背景颜色。但这没有用。这是我的代码。但这没用..

    function color (){
        var color = ["#02245c", "green", "blue", "red", "yellow"];
        var i;
        for (var i = 0; i < color.length; i++) {
          color[i];
          document.body.style.background = color[i];
        }
      }
丹特沙尔:

恭喜您学习JS。

为您构建解决方案,这是我想到的最简单的方法。希望你喜欢。

const button = document.querySelector('button');

var currentColorIndex = 0;
button.onclick = () => changeColor();

function changeColor () {
  var color = ["#02245c", "green", "blue", "red", "yellow"];

  // You dont need a loop, this is what will change the color every time the function gets called.
  if( currentColorIndex < color.length - 1 ) {
    currentColorIndex++;
  } else {
    currentColorIndex = 0;
  }
  
  button.style.background = color[currentColorIndex];
}
<!-- HTML expanding (Emmet):
  - type html:5 and press Tab;
  - type div>h1#header and press Tab;
-->
<button>Click me</button>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章