Add Fade Effect in Slideshow (Javascript)

前端 未结 4 1577
情书的邮戳
情书的邮戳 2020-12-29 16:19

I have created a JavaScript Slideshow, but I don\'t know how to add the fade effect. Please tell me how to do it, and please tell in JavaScript only, no jQuery!

Code

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 17:12

    Much shorter than Ninja's solution and with hardware accelerated CSS3 animation. http://jsfiddle.net/pdb4kb1a/2/ Just make sure that the transition time (1s) is the same as the first timeout function (1000(ms)).

    Plain JS

    var imgArray = [
        'http://placehold.it/300x200',
        'http://placehold.it/200x100',
        'http://placehold.it/400x300'],
        curIndex = 0;
        imgDuration = 3000;
    
    function slideShow() {
        document.getElementById('slider').className += "fadeOut";
        setTimeout(function() {
            document.getElementById('slider').src = imgArray[curIndex];
            document.getElementById('slider').className = "";
        },1000);
        curIndex++;
        if (curIndex == imgArray.length) { curIndex = 0; }
        setTimeout(slideShow, imgDuration);
    }
    slideShow();
    

    CSS

    #slider {
        opacity:1;
        transition: opacity 1s; 
    }
    
    #slider.fadeOut {
        opacity:0;
    }
    

提交回复
热议问题