Как добавить анимацию к фотографиям, меняющимся каждые 3 секунды? - PullRequest
0 голосов
/ 27 мая 2020

Картинки меняются каждые 3 секунды. Я бы хотел добавить к фото простую анимацию при смене. Желательно ваниль js.

let index = 1;
const changeImg = () => {
  index++;
  img.setAttribute('src', `img/img${index}.png`);

  if (index === 3) {
    index = 0;
  }
};
setInterval(changeImg, 3000);

Ответы [ 2 ]

0 голосов
/ 27 мая 2020

Как вы предложили пример ванили JavaScript (без библиотек), здесь вы go.

(function slideShow() {
  let imgs = [
    "https://picsum.photos/id/237/200/300",
    "https://picsum.photos/id/238/200/300",
    "https://picsum.photos/id/239/200/300"
  ];

  let index = 0;
  const frontImg = document.getElementById("slideshow__img--front");
  const backImg = document.getElementById("slideshow__img--back");
  frontImg.src = imgs[index];

  const changeSlideShowImg = () => {
    const currImgSrc = imgs[index];
    index++;
    if (index >= imgs.length) index = 0;
    const newImgSrc = imgs[index];

    backImg.src = newImgSrc;
    frontImg.classList.add("slideshow__img--fadeout");

    setTimeout(() => {
      frontImg.src = newImgSrc;
      frontImg.classList.remove("slideshow__img--fadeout");
    }, 500);
  };

  setInterval(changeSlideShowImg, 3000);
})()
.slideshow {
  width: 200px;
  height: 300px;
  position: relative;
}

.slideshow__img {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 1;
}

#slideshow__img--front {
  z-index: 2;
}

.slideshow__img.slideshow__img--fadeout {
  transition: opacity 0.5s ease-in;
  opacity: 0;
}
<div class="slideshow">
  <img id="slideshow__img--front" class="slideshow__img" />
  <img id="slideshow__img--back" class="slideshow__img" />
</div>
0 голосов
/ 27 мая 2020

Если вы используете что-то вроде animate. css или создаете свой собственный класс анимации, вы можете сделать это следующим образом:

(Я предполагаю, что вы получаете изображение с помощью селектора запросов / getElementById)

let index = 1;
const changeImg = () => {
  index++;
  img.classList.add('animate__animated');
  img.classList.add('animate__bounce');

  setTimeout(() => {
    img.setAttribute('src', `img/img${index}.png`);

    img.classList.remove('animate__animated');
    img.classList.remove('animate__bounce');
  }, 300); // This delay is assuming the animation duration is 300ms, you need to change this to the length of the animation



  if (index === 3) {
    index = 0;
  }
};
setInterval(changeImg, 3000);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...