How do I loop this animation indefinitely?

2019-02-19 23:08发布

I'm kinda new to jquery and I managed to program a small animation which fades in and fades out two pictures.

My problem now is that after it has gone round the cycle, it just stops. I need it to start from the beginning again when it reaches the end. It should just continue.

Here's the code

$(document).ready(function() {
    $('img.banner1').fadeOut(5000);
    $('img.banner2').delay(1000).fadeIn(5000);
    $('img.banner2').delay(1000).fadeOut(5000);
    $('img.banner1').fadeIn(5000).delay(1000);
});

2条回答
倾城 Initia
2楼-- · 2019-02-19 23:31

You could move it to a function and invoke with setInterval.

function AnimateBanners() {
    $('img.banner1').fadeOut(5000);
    $('img.banner2').delay(1000).fadeIn(5000);
    $('img.banner2').delay(1000).fadeOut(5000);
    $('img.banner1').fadeIn(5000).delay(1000);
}

$(document).ready(function() {
    setInterval(AnimateBanners, 10000); //Will run every 10 seconds
});

查看更多
Rolldiameter
3楼-- · 2019-02-19 23:37

This code will restart the function after the 1000ms delay after starting the final fadeIn. You might want a longer delay though since you take 5000ms to fade that banner in...

function animateBanners() {
    $('img.banner1').fadeOut(5000);
    $('img.banner2').delay(1000).fadeIn(5000);
    $('img.banner2').delay(1000).fadeOut(5000);
    $('img.banner1').fadeIn(5000).delay(1000).queue(animateBanners);
}

$(document).ready(function() {
    animateBanners();
});
查看更多
登录 后发表回答