如何使用 3 个不同的数组更改 3 个 div 的颜色

当我单击“更改主题”按钮时,如何使用提供的 3 个数组更改 3 个 div 的颜色。


<script>

var colors = ['red', 'green', 'blue']

var colors1 = ['teal', 'brown', 'tan']

var colors2 = ['orange', 'purple', 'black'];

var boxed = document.querySelectorAll(".box");

var button = document.querySelector("button");


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

   for (i = 0; i < boxed.length; i++) {

        boxed[i].style.backgroundColor = colors[Math.floor(Math.random() * 3)];

        boxed[i].style.width = '100px';

        boxed[i].style.height = '100px';

        boxed[i].style.display = 'inline-block';

  }

});

button.style.cursor = "pointer";

</script>


holdtom
浏览 99回答 2
2回答

慕后森

我想你想要这样的东西-更新了需求的代码var colors = [&nbsp; ['red', 'green', 'blue'],&nbsp; ['teal', 'brown', 'tan'],&nbsp; ['orange', 'purple', 'black']]var boxed = document.querySelectorAll(".box");var button = document.querySelector("button");button.addEventListener("click", function () {&nbsp; &nbsp; let colorIndex = Math.floor(Math.random() * 3);&nbsp; &nbsp;for (i = 0; i < boxed.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; boxed[i].style.backgroundColor = colors[colorIndex][i];&nbsp; &nbsp; &nbsp; &nbsp; boxed[i].style.width = '100px';&nbsp; &nbsp; &nbsp; &nbsp; boxed[i].style.height = '100px';&nbsp; &nbsp; &nbsp; &nbsp; boxed[i].style.display = 'inline-block';&nbsp; }});button.style.cursor = "pointer";.box {&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; display: inline-block;&nbsp; background: gray;}<div class="box">1</div>&nbsp; <div class="box">2</div>&nbsp; <div class="box">3</div>&nbsp; <button>Theme</button>

动漫人物

类似的东西?const colors= [ ['red', 'green', 'blue']&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; , ['teal', 'brown', 'tan']&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; , ['orange', 'purple', 'black'] ]&nbsp; ,&nbsp; &nbsp;boxed&nbsp; = document.querySelectorAll(".box")&nbsp; ,&nbsp; &nbsp;button = document.querySelector("button")&nbsp; ;button.onclick=_=>&nbsp; {&nbsp; let colorN = Math.floor(Math.random() *3)&nbsp; boxed.forEach((box,i)=>&nbsp; &nbsp; {&nbsp; &nbsp; box.style.backgroundColor = colors[colorN][i];&nbsp; &nbsp; })&nbsp; }.box {&nbsp; display: inline-block;&nbsp; width: 100px;&nbsp; height: 100px;&nbsp; background-color: lightgrey;}<div class="box">box 1</div><div class="box">box 2</div><div class="box">box 3</div><button>change Colors</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5