Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

html - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...