0

Нужно, чтобы по клику на одну из двух кнопок проигрывалась анимация CSS. Для этого используется обработчик событий jQuery и функции addClass() и removeClass() со значением класса анимации. Но анимация проигрывается только один раз, по первому клику. Как сделать её постоянное повторение?

var colors = ['black', 'red', 'green'];
var counter = 0;

$('#prev').click(function() {
  changeBackground(-1);
});
$('#next').click(function() {
  changeBackground(1);
});

function changeBackground(num) {

  counter += num;
  if (counter >= colors.length) counter = 0;
  if (counter < 0) counter = colors.length - 1;
  $('.background').css('background-color', colors[counter]);

  $('.background').removeClass('fade');
  $('.background').addClass('fade');
}
.background {
  width: 200px;
  height: 200px;
  background-color: black;
}

#prev,
#next {
  position: relative;
  top: 90px;
}

#prev {
  float: left;
}

#next {
  float: right;
}

.fade {
  animation-name: fade;
  animation-duration: 1.5s;
}

@keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section class="background">
  <button id="prev">Prev</button>
  <button id="next">Next</button>
</section>

1 ответ 1

0

Код js:



    var colors = ['black', 'red', 'green'], counter = 0;

    $('#prev').click(function() {
      changeBackground(-1);
    });
    $('#next').click(function() {
      changeBackground(1);
    });

    function changeBackground(num) {
      counter += num;
      if (counter >= colors.length) counter = 0;
      if (counter < 0) counter = colors.length - 1;

      var elem = $('.background');
      elem.css('background-color', colors[counter]);

      if (elem.css('animationName') === "fade")
        elem.css('animationName', 'fade2');
      else
        elem.css('animationName', 'fade');
    }

Код css:



    .fade {
      animation-duration: 1.5s;
    }

    @keyframes fade {
      from {
        opacity: .4
      }
      to {
        opacity: 1
      }
    }

    @keyframes fade2 {
      from {
        opacity: .4
      }
      to {
        opacity: 1
      }
    }

Ваш ответ

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

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.