Разбор сложного переключателя цветов из массива
Есть скрипт, который при клике поочередно меняет цвет двум блокам. ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀ .Но я не могу понять, почему при первом клике index = 3, а не 0?
В итоге при первом клике на блок получается index = 3 + 1 % 4 = 0⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ берется цвет из массива под позицией 0 ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀ ⠀⠀ Ведь должно же быть при первом клике index = 0 + 1 % 4 = 1.
Я запутался, помогите понять почему при первом клике index = 3, а не 0? ⠀⠀⠀⠀⠀⠀⠀⠀⠀ Внизу я пометил странную строчку кода комментарием
let a = document.querySelector('.main');
let colors = ['red', 'black', 'white', '' ];
for(let b of document.querySelectorAll('.block1, .block2')){
b.addEventListener('click', click_block);
}
function click_block(e){
let index = colors.indexOf(e.currentTarget.style.backgroundColor);
alert(e.currentTarget.style.backgroundColor = colors[(index +1 ) % 4]);// Почему при 1 клике index = 3, а не 0?
}
body{
background: orange;
user-select:none;
}
.main{
margin-top: 100px;
margin-left: 200px;
position:relative;
height: 100px;
}
.block0{
height: 100%;
width:250px;
background: white;
text-align:center;
}
.block1{
height: 100%;
width:250px;
background: gray;
text-align:center;
}
.block2{
height: 100%;
width:250px;
background: gold;
text-align:center;
}
<div class="main">
<div class ='block0'>
1 блок - Цвета нет
</div>
<div class="block1">
2 блок - Цвет работает +
</div>
<div class="block2">
3 блок - Цвет работает +
</div>
</div>
Ответы (2 шт):
Потому что style.backgroundColor - пустая строка, которая есть в Вашем массиве.
function click_block(e) {
console.log(e.currentTarget.style.backgroundColor);
...
Я переписал код, вот что у меня получилось. Теперь мы забираем цвета в зависимости от того, что лежит в массиве colors по определенному условию. Возможно это стоит доработать, но это то, что вам нужно.
//Массив цветов.
let colors = ['rgb(255, 0, 0)', 'rgb(0, 0, 0)', 'rgb(255, 255, 255)'];
//Наше правило.
const rules = 1 % 4;
//Текущий цвет в массиве colors
let currentBackgroundColor = '';
//Функция для рандомного числа.
const getRandom = (min, max) => Math.floor(Math.random() * (max - min)) + min;
//Функция которая получает цвет формата rgb.
const getColorStyles = (element) =>
window.getComputedStyle(element, null).getPropertyValue('background-color');
//Наше рандомное число, по нему устанавливаем дефолтный цвет.
const initialColorNumber = getRandom(0, colors.length - 1); //
addEventListener('click', (event) => {
const block = event.target.closest('.block');
if (!block) return;
//Обновляем цвет.
currentBackgroundColor = getColorStyles(block);
//Проверяем, что если отсутствует цвет из массива цветов, устанавливаем цвет рандомный.
if (!colors.includes(currentBackgroundColor)) {
block.style.backgroundColor = colors[initialColorNumber];
//Обновляем цвет.
currentBackgroundColor = getColorStyles(block);
}
//Текущий индекс по которому устанавливаем цвет.
let currentIndex = colors.indexOf(currentBackgroundColor);
//Индекс согласно правилу.
let moduleIndexColor = currentIndex + rules;
//Учитываем, что такого index может не быть, возвращаем правду или ложь.
const isMax = moduleIndexColor > colors.length - 1 ? true : false;
if (isMax) {
moduleIndexColor = 0;
}
block.style.backgroundColor = colors[moduleIndexColor];
//Обновляем цвет.
currentBackgroundColor = getColorStyles(block);
});
<body>
<div class="main">
<div class="block">1 блок - Цвет работает +</div>
<div class="block">2 блок - Цвет работает +</div>
<div class="block">3 блок - Цвет работает +</div>
</div>
<script src="script.js"></script>
</body>
Старый вариант, тут мы получаем index от кол-во элементов.
const blocks = document.querySelectorAll('.block');
const moduleIndex = 0;
const colors = ['red', 'black', 'white', 'white'];
blocks.forEach((block, index) => {
block.addEventListener('click', () => {
const moduleIndex = (++index) % 4;
block.style.backgroundColor = colors[moduleIndex];
})
})
<body>
<div class="main">
<div class="block">1 блок - Цвет работает +</div>
<div class="block">2 блок - Цвет работает +</div>
<div class="block">3 блок - Цвет работает +</div>
</div>
<script src="script.js"></script>
</body>
Генератор для цветов.
//Массив цветов.
const colors = [];
const getRandomRgb = () => {
const num = Math.round(0xffffff * Math.random());
const r = num >> 16;
const g = (num >> 8) & 255;
const b = num & 255;
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
};
for (let i = 0; i < 256; i++) {
colors.push(getRandomRgb());
}