首页 > 解决方案 > 单击以轻松转换图像

问题描述

我有一个英雄形象,点击箭头按钮(上一个/下一个)会改变。这部分效果很好,但是变化很大。我正在尝试在每个图像之间添加一个轻松过渡,以便它们快速淡入或淡出。有没有一种简单的方法可以使用下面的 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>

标签: javascripttransitionfadein

解决方案


由于src无法在单个 IMGElement 上转换更改,因此您需要预先创建所有图像。这也将防止在浏览器仍在加载下一个图像时看到闪烁的白色。

使用 GPU 加速 CSStransition和 CSStransform来为您的图像属性设置动画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>


推荐阅读