在JavaScript中,如何为模态画廊中的每张图片添加动画效果?

In JavaScript, how can I add animation effect on every image in a modal gallery?

我有一个图片库,每一个图片都会在点击时以模态模式打开。我想为它们中的每一个添加动画效果,以便在单击下一个和上一个按钮时显示。我将动画样式添加到我的 JS 代码中,但是它没有按预期工作。它仅在第一次点击时有效,其余的无效。

这是我的代码:


    var prev = document.querySelector("#prev");
    var next = document.querySelector("#next");
    next.addEventListener("click", nextImage);
    modalImg.addEventListener("click", nextImage);
    prev.addEventListener("click", previousImage);

    function nextImage() {
      if (currentIndex < imgArr.length - 1) {
        currentIndex++;
        modalImg.src = imgArr[currentIndex].style.backgroundImage
          .slice(4, -1)
          .replace(/"/g, "");
      }
      modalImg.style.animation = "fadeInLeft .4s both";
    }

    function previousImage() {
      if (currentIndex > 0) {
        currentIndex--;
        modalImg.src = imgArr[currentIndex].style.backgroundImage
          .slice(4, -1)
          .replace(/"/g, "");
      }
      modalImg.style.animation = "fadeInLeft .4s both";
    }

    @keyframes fadeInLeft {
      0% {
        opacity: 0;
        -webkit-transform: translateX(-20px);
        -ms-transform: translateX(-20px);
        transform: translateX(-20px);
      }
      100% {
        opacity: 1;
        -webkit-transform: translateX(0);
        -ms-transform: translateX(0);
        transform: translateX(0);
      }
    }

您可以通过 属性 animationName 操纵动画或通过 class 定义动画的名称操纵来实现它。

example

无论如何你都应该在动画完成后移除它

function onAnimationEnd(){
/*
  // Options 1: Manipulate class name
  this.classList.remove('fade')
*/
  imgContainer.style.animationName = 'none';
}
imgContainer.addEventListener('animationend', onAnimationEnd);

您可以简化以避免重复:

const prev = document.querySelector("#prev");
const next = document.querySelector("#next")
prev.addEventListener("click", prevImage);
next.addEventListener("click", nextImage);
modalImg.addEventListener("click", nextImage);

function animate(i) {
  modalImg.src = imgArr[i].style.backgroundImage
    .slice(4, -1)
    .replace(/"/g, "");
  modalImg.style.animationName = "fadeInLeft";
}

function nextImage() {
  currentIndex = (currentIndex + 1) % imgArr.length;
  animate(currentIndex)
}

function prevImage() {
  currentIndex = (currentIndex + imgArr.length - 1) % imgArr.length;
  animate(currentIndex)
}

或者只使用一个事件监听器(不需要 prevnext 变量):

function animate(i) {
  modalImg.src = imgArr[i].style.backgroundImage
    .slice(4, -1)
    .replace(/"/g, "");
  modalImg.style.animationName = "fadeInLeft";
}

function showImage(elem) {
    if (elem.id === "next" || elem.id === "modalImg") {
        currentIndex = (currentIndex + 1) % imgArr.length;
    } else if (elem.id === "prev") {
        currentIndex = (currentIndex + imgArr.length - 1) % imgArr.length;
    } else {
        return currentIndex
    }
    animate(currentIndex)
}

window.addEventListener("click", function(e) {
    showImage(e.target)
});