Tło możesz ustawić za pomocą tablicy i przez losowanie indeksu koloru, wtedy nie musisz używać if-ów, żeby ustawić wylosowany kolor.
<style>
.box-random-color {
width: 200px;
height: 200px;
}
</style>
<div class="box-random-color"></div>
const colors = [ 'red', 'green', 'blue' ];
const box_random_color = document.querySelector('.box-random-color');
const color_random_index = parseInt(Math.random() * colors.length);
box_random_color.style.backgroundColor = colors[color_random_index];
i korzystając z tej samej tablicy możesz ustawić tło dla box-ów za pomocą, których będziesz wybierał kolor.
<style>
.box-choice-color {
display: inline-block;
width: 100px;
height: 100px;
}
</style>
<div class="box-choice-color"></div>
<div class="box-choice-color"></div>
<div class="box-choice-color"></div>
const colors = [ 'red', 'green', 'blue' ];
const boxes_choice_color = document.querySelectorAll('.box-choice-color');
boxes_choice_color.forEach((box, index) => {
box.style.backgroundColor = colors[index];
});
teraz przez odwołanie do e.target klikniętego przycisku możesz sprawdzić kolory.
<style>
* {
margin: 0.5em;
}
.box-random-color {
width: 200px;
height: 200px;
}
.box-choice-color {
display: inline-block;
width: 100px;
height: 100px;
cursor: pointer;
}
.info {
font: 700 1.4em monospace;
color: black;
}
</style>
<div class="box-random-color"></div>
<div class="box-choice-color"></div>
<div class="box-choice-color"></div>
<div class="box-choice-color"></div>
<div class="info"></div>
const colors = [ 'red', 'green', 'blue' ];
const box_random_color = document.querySelector('.box-random-color'),
boxes_choice_color = document.querySelectorAll('.box-choice-color'),
info = document.querySelector('.info');
const color_random_index = parseInt(Math.random() * colors.length);
box_random_color.style.backgroundColor = colors[color_random_index];
boxes_choice_color.forEach((box, index) => {
box.style.backgroundColor = colors[index];
box.addEventListener('click', checkColor);
box.addEventListener('mouseout', clearInfo); // Opcjonalnie
});
function checkColor(e) {
if (e.target.style.backgroundColor == box_random_color.style.backgroundColor) {
info.textContent = 'Prawidłowy kolor';
} else {
info.textContent = 'To nie ten kolor';
}
}
function clearInfo() {
info.textContent = '';
}
Inny przykład on-line.