3

Помогите пожалуйста дописать код, при первом наведении мышки на блок цвет фона должен становиться красный, при отводе мышки блок становиться снова фиолетовый (фиолетовый по умолчанию стоит в CSS), при втором наведении - блок становится желтым, при третьем - зеленым. При следующем наведении все начинается сначала: красный, желтый, зеленый. Так должно происходить бесконечно по кругу.

Код JS:

document.querySelector('.box').onmouseout = function () {
    this.style.backgroundColor = '';
}

document.querySelector('.box').onmouseover = function () {
    let countMouseOver = 0;
    while (true) {
        if (countMouseOver == 0) {
            event.target.style.backgroundColor = 'black';
            countMouseOver++;
        }
        if (countMouseOver == 1) {
            this.style.backgroundColor = 'yellow';
            countMouseOver++;
        }
        if (countMouseOver == 2) {
            this.style.backgroundColor = 'green';
            countMouseOver = 0;
        }

    }
}

2 ответа 2

3

const box = document.querySelector('.box');
// это будет переменная счетчик
let cursor = 0;
const colors = ['#f72500', '#fefd00', '#1b7e00'];

box.onmouseover = function() {
  box.style.backgroundColor = colors[cursor++];
  // здесь мы берем остаток от деления на длину массива цветов
  // при достижении длины массива 3 % 3 = 0 => начинаем сначала
  cursor %= colors.length;
};

box.onmouseout = function() {
  box.style.backgroundColor = '';
};
.box {
    margin: 10px auto;
    height: 250px;
    width:  250px;
    border: 1px solid black;
    background-color: #7d1580;
}
<div class='box'></div>

1
  • Большое спасибо!
    – user388755
    15 мая 2020 в 10:40
3

Ну приблизительно вот так

let box = document.querySelector('.box');
let colors = ['#f72500', '#fefd00', '#1b7e00'];

box.dataset.current = 0;

box.onmouseout = function() {
  this.style.backgroundColor = '';
}

box.addEventListener('mouseover', function(event) {
  this.style.backgroundColor = colors[this.dataset.current];
  this.dataset.current++;
  if (this.dataset.current >= colors.length) {
    this.dataset.current = 0;
  }
});
.box {
  margin: 10px auto;
  height: 250px;
  width: 250px;
  border: 1px solid black;
  background-color: #7d1580;
}
<div class="box"></div>

В вашем варианте бесконечный цикл абсолютный лишний, а индекс текущего цвета необходимо декларировать вне события

1
  • Большое спасибо!
    – user388755
    15 мая 2020 в 10:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.