简体   繁体   中英

Laggy fade in fade out for a background

I want the background image for my web page to fade out as the next image fades in, i do it like so:

    var backgrounds = [];
    backgrounds[0] = './img/bg.jpg';
    backgrounds[1] = './img/bg2.jpg';
    backgrounds[2] = './img/bg3.jpg';



function changeBackground() {
    currentBackground++;
if(currentBackground > backgrounds.length-1) currentBackground = 0;

$('.bgContainer').fadeOut(1500,function() {
    $('.bgContainer').attr('src', backgrounds[currentBackground]);
    $('.bgContainer').fadeIn(3000);
});



    setTimeout(changeBackground, 5000);
}

and its working fine, but each time the next image fades in any other elements start dropping the frames and become really laggy. is there any way to reduce the frame drops?

.bgContainer{
position:fixed;
z-index: -1;
width:100vw;
height:100%;
top:0;
}

<img class="bgContainer" src = "./img/bg.jpg">

I don't know if you can use css transitions for browser compatibility but you could try something like:

.bgContainer {
    transition: opacity 1500ms ease-in-out;
}

and

$('.bgContainer').css('opacity', 0);

setTimeout(function() {
    $('.bgContainer').attr('src', backgrounds[currentBackground]);
    $('.bgContainer').css('opacity', 1);
}, 1500);

This way you are not using javascript to change css properties but use CSS3 to fade your backgrounds opacity.

Way less laggy then javascript animations but will only work on modern browsers. ie10+

Use css transitions rather than jQuery. I found this especially true for mobile devices.

Add a class via javascript or jQuery and apply the effects u want too that class.

Take a look at this if u want to more about CSS transitions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM