几秒钟后图像更改期间如何添加FadeIn / FadeOut JavaScript效果

时间:2019-05-12 23:51:56

标签: javascript html

我有2张图片,几秒钟后就会更改。我想在这些图像更改时添加FadeIn/FadeOut效果。

<script>
    var img_tracker = "icon1";

    function changeImg()
    {
        var pic = document.getElementById("img1");

        if (img_tracker == "icon1") {
            pic.src = "images/icon1.png";
            img_tracker = "icon2.png";
        } else {
            pic.src = "images/icon2.png";
            img_tracker = "icon1";
        }
    }

    setInterval("changeImg()", 2000);
</script>

<img src="images/icon1.png" id="img1">

这是我当前的代码,是否可以在每次更改图片时添加fadeOut/fadeIn

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用CSS过渡。然后,您可以使用fade-out周期性地setInterval()当前图像。图像完全fade-out之后,您可以更改图像来源和fade-in。要检测fade-out过渡,可以在"transitionend"事件上使用addEventListener()

示例:

var img_tracker = "icon1";
var pic = document.getElementById("img1");

function changeImg()
{
    if (img_tracker == "icon1")
    {
        pic.src = "https://via.placeholder.com/150/FF0000";
        img_tracker = "icon2";
    }
    else
    {
        pic.src = "https://via.placeholder.com/150/0000FF";
        img_tracker = "icon1";
    }
}

function fadeIn()
{
    pic.classList.remove("fade-out");
    pic.classList.add("fade-in");    
}

function fadeOut()
{
    pic.classList.remove("fade-in");
    pic.classList.add("fade-out");

    pic.addEventListener("transitionend", function x()
    {
        pic.removeEventListener("transitionend", x);
        changeImg();
        fadeIn();
    });
}

setInterval(fadeOut, 5000);
.fade {
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.fade-out {
  opacity: 0;
}

.fade-in {
  opacity: 1;
}
<img src="https://via.placeholder.com/150/0000FF"
     id="img1"
     class="fade">