Вопрос

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.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top