简体   繁体   中英

How do I add FadeIn/FadeOut javascript effect during images change after a few seconds

I have 2 images that changes after a few seconds. I want to add a FadeIn/FadeOut effect when these images changes.

<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">

That is my current code, is there any way I can add fadeOut/fadeIn on every image change?

One possible solution is to use CSS transitions. Then, you can fade-out the current image periodically with setInterval() . Once the image is completely fade-out you can change the image source and fade-in . To detect the fade-out transition you can use addEventListener() over the "transitionend" event.

Example:

 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"); // Add listener to the "transitionend" event. pic.addEventListener("transitionend", function x() { // Remove the previously added listener, change // the image and fade-in the new image. 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 id="img1" src="https://via.placeholder.com/150/0000FF" class="fade">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM