单击以轻松过渡更改图像

问题描述

我有一个英雄图像,通过单击箭头按钮(上一个/下一个)可以更改。这部分效果很好,但是变化很大。我正在尝试在每个图像之间添加轻松过渡,以使它们快速淡入或淡出。有没有使用下面的JS做到这一点的简单方法?我是初学者。谢谢!

<script>
    $( document ).ready(function() {

        var images = [
            "tophalf-b.jpg","tophalf-a.jpg",];

        var imageIndex = 0;

        $("#prevIoUs").on("click",function(){          
            imageIndex = (imageIndex + images.length -1) % (images.length);    
            $("#image").attr('src',images[imageIndex]);

        });

        $("#next").on("click",function(){
            imageIndex = (imageIndex+1) % (images.length);    
            $("#image").attr('src',images[imageIndex]);

        });

        $("#image").attr(images[0]);

    });
</script>

解决方法

好的。

$("#previous").on("click",function(){          
    $("#image").fadeOut(500,(function() {
        imageIndex = (imageIndex + images.length -1) % (images.length);                
        $("#image").attr('src',images[imageIndex]);
    }));            
    $("#image").fadeIn();
});

500是动画时代。接下来,我们在其中更改图像的回调函数。最后,淡入图像元素。

如果您想进行“淡入淡出”,请转到the page

,

由于无法在单个IMGElement上转换src,因此需要预先创建所有图像。当浏览器仍在加载下一张图像时,这样还可以防止看到 white 闪烁。

使用GPU加速的CSS transition和CSS transform为图像的opacity属性设置动画。
使用 JS只是切换CSS ".is-active",作为回报,您的图像会褪色:

jQuery(($) => {

  const images = [
    "https://placehold.it/150x150/0bf?text=One","https://placehold.it/300x150/bf0?text=Two","https://placehold.it/300x150/fb0?text=Three",];
  
  const $img = $(images.map((src) => $("<img>",{src: src})[0])); // Generate IMGs
  const $gal = $("#images").append($img); // Append them to a parent
  const tot = images.length;
  const anim = () => $img.removeClass("is-active").eq(idx).addClass("is-active");
  let idx = 0;

  $("#prev").on("click",() => {
    idx = (idx + tot - 1) % tot;
    anim();
  });

  $("#next").on("click",() => {
    idx = (idx + 1) % tot;
    anim();
  });

  anim(); // Init Animate!

});
#images {
  height: 150px;
  position: relative;
}

#images img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: contain; /* Scale image to fit parent element */
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.4s; /* Use GPU accelerated properties */
}

#images img.is-active {
  opacity: 1;
  pointer-events: auto;
}
<div id="images"></div>
<button type="button" id="prev">&larr;</button>
<button type="button" id="next">&rarr;</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>