Fading images - Where to call .fadeIn and .fadeOut?

做~自己de王妃 提交于 2019-12-11 17:53:01

问题


Been hitting my head a while with this one. I'm a total novice in JavaScript and jQuery. After a lot of trial and error I eventually managed to write a function to change the src attribute of an image to create a slideshow as such:

    $(function () {
            var slideshow = $("#img_slideshow");
            var images = [
            'img/slideshow1.jpg', 
            'img/slideshow2.jpg',
            'img/slideshow3.jpg'];
            var current = 0;

            function nextSlide() {
                slideshow.attr(
                'src',
                images[current = ++current % images.length]);

                setTimeout(nextSlide, 5000);
            }
            setTimeout(nextSlide, 5000);
        });

This works perfectly, changes the image every 5 seconds. What I wanted, was a fade transition between them. I tried calling .fadeIn and .fadeOut in several places I find logic, such as next to setTimeout (probably wrong) but nothing will work. Can anyone help? And I'd be grateful to have a simple explanation of where it should be called, could help a lot of folks out there. Thanks.


回答1:


It should be done like this (using the callbacks) -

function nextSlide() {
    slideshow.fadeOut(function() {
        $(this).attr('src',images[current = ++current % images.length]).fadeIn();
    });

    setTimeout(nextSlide, 5000);
}

This insures that the source is not changed until the fade out is complete. The source changes and the fade in then happens. This will not be a cross-fade though.



来源:https://stackoverflow.com/questions/23230506/fading-images-where-to-call-fadein-and-fadeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!