Pergunta

I have created a little project where theres an image slideshow (transition) where on the page load, image opacities are changed, to create a slideshow effect.

It works really well, however I'm interested in knowing how I can upgrade my code so that it just loops back to the start, so the slideshow is never ending, Help will be greatly appreciated, here is what I have tried already:

$(document).ready(function() {
    $("#image1").fadeTo(2000 , 0, function() {
        $("#image2").fadeTo(2000 , 1, function(){
            $("#image3").fadeTo(3000, 1, function(){

            });
        });
    });
});

http://jsfiddle.net/pYECC/4/

Foi útil?

Solução 2

Heres a nice little solution - http://jsfiddle.net/pYECC/7/

$(document).ready(function() {
    var images = ["image1", "image2", "image3"];
    var x = 0;

    setInterval(function () {
        $("#" + images[x]).fadeOut(1000, function () {
            x++;
            if(x == 3)
                x = 0;
            $("#" + images[x]).fadeIn(1000);
        });
    }, 3000);  
});

With this you need to remove opacity from your CSS. You need to make images 2 & 3 display: none; by default.

Outras dicas

<script>       
    var maxImgNum = null;
    var imgT = null;
    var transitionSpeed = 4000;
    var transitionDelay = 600;

    $(document).ready(function(){
        var $slideshowImgs = $("#anim_cont").find("img");
        var maxImgNum = $slideshowImgs.length;
        $slideshowImgs.each(function(i, obj){
            $(obj).css("z-index", maxImgNum - i);
    });
    imgT = window.setTimeout(function(){animateSlideshow()},transitionSpeed);          
});

function animateSlideshow(){

    $(".anim")
        .eq(0)
            .fadeOut(transitionDelay, function(){
                $(this).appendTo("#anim_cont")
                $(".anim").each(function(i, v){
                    $(this)
                        .css("z-index", maxImgNum-i)
                        .css("display", "block");
                })
                imgT = window.setTimeout(function(){animateSlideshow()}, transitionSpeed);

            });
}
</script>




<div id="anim_cont">
    <img src="http://eclipse-developers.com/download.jpg" id="image1" class="anim"/> 
    <img src="http://eclipse-developers.com/download2.jpg" id="image2" class="anim"/> 
    <img src="http://eclipse-developers.com/download3.jpg" id="image3" class="anim"/> 
</div>

You could wrap all the slideshow transitions into a function, and then pass that function as the callback to the last transition. That would cause it to loop indefinitely.

Alternatively, you could use CSS animations to achieve this effect, as they natively support looping and browsers can often better optimize them for performance vs script-based transitions. You could then detect browser support for CSS animations and fall back to the jQuery transitions if support is missing.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top