Vous devez utiliser document.querySelectorAll
pour obtenir toutes les classes avec box
Ensuite, vous ferez la boucle forEach et vous appellerez aussi cette boucle getRandomColor
pour obtenir des couleurs différentes appliquées individuellement.
Vous pouvez en savoir plus sur les boucles avec querySelectorAll
aquí et expliqué en détail
Exécutez l'extrait ci-dessous pour voir que tout fonctionne.
const colorBtn = document.querySelector('#btn-1')
const boxes = document.querySelectorAll('.box')
var running = false
function getRandomColor() {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function start() {
if (running) {
boxes.forEach(color => {
let newColors = getRandomColor()
color.style.background = newColors
})
setTimeout(start, 500)
}
}
colorBtn.addEventListener('click', function(e) {
colorBtn.innerText = 'Stop'
if (running) {
running = false
colorBtn.innerText = 'Change Color'
} else {
running = true
start()
}
})
* {
box-sizing: border-box;
padding: 0;
margin: 0;
font-family: 'Oswald', sans-serif;
}
body {
background: radial-gradient(circle, rgba(51, 51, 51, 1) 0%, rgba(29, 19, 19, 1) 100%);
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 2rem auto;
padding-top: 1rem;
color: #fff;
max-width: 60rem;
}
.btn-container {
width: 60%;
margin: 0 auto;
display: flex;
justify-content: center;
}
.btn {
padding: 1rem 3rem;
background: linear-gradient(13deg, rgba(34, 81, 249, 1) 0%, rgba(19, 246, 255, 1) 100%);
border: none;
border-radius: 4px;
font-size: 1.2rem;
outline: none;
cursor: pointer;
color: #fff;
}
.box-container {
width: 100%;
height: 100%;
background: red;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
.box {
background: blue;
padding: 3rem 3rem;
}
#box-1 {
background: white;
}
#box-2 {
background: red;
}
#box-3 {
background: green;
}
#box-4 {
background: yellow;
}
#box-5 {
background: orange;
}
#box-6 {
background: blue;
}
<div class="box-container">
<div class="box" id="box-1"></div>
<div class="box" id="box-2"></div>
<div class="box" id="box-3"></div>
<div class="box" id="box-4"></div>
<div class="box" id="box-5"></div>
<div class="box" id="box-6"></div>
</div>
<div class="container">
<div class="btn-container">
<button class="btn" id="btn-1">Change Color</button>
</div>
</div>