How can I smoothly transition CSS background images?

后端 未结 3 922
攒了一身酷
攒了一身酷 2021-02-15 13:25

The main solution out there is:

\"Just throw a loading screen up until the page is loaded\".

But my goal is to build pages that pres

3条回答
  •  臣服心动
    2021-02-15 13:42

    As noted in the comments by @dandavis, there's actually a CSS transition property : background-image.

    The solution, utilizing the CSS background transition property:

    1. create two background images of the same size: one transparent & one that's intended. (If you don't make them the same size, you'll get this effect!);

    2. use transition: background-image 1s to cause the transition effect

    3. use Javascript to preload the image and reset the background image when it's ready. CSS will take care of the rest.

    Notable Limitations

    • This does not allow for background-size manipulation ( this results in a very weird effect).

    • The images, as mentioned, must be the same size.


    Working Example

    var image = new Image();
    image.onload = function () {
            $(".element").css("background-image", "url('" + image.src + "')");
    }
    
    image.src = "https://c1.staticflickr.com/3/2439/3728897793_ff1c78c5d9.jpg"; //image to be transitioned to
    html{
        width:100%;
        height:100%;
    }
    body{
        width:100%;
        height:100%;
        padding:0px;
        margin:0px;
    }
    .element{
        width:100%;
        height:100%;
        background-image:url('http://i.imgur.com/HRV3DsM.jpg');
        -webkit-transition: background-image 5s;
    }

提交回复
热议问题