jQuery How do you get an image to fade in on load?

前端 未结 13 1625
情话喂你
情话喂你 2020-11-29 04:21

All I want to do is fade my logo in on the page loading. I am new today to jQuery and I can\'t managed to fadeIn on load please help. Sorry if this question has already been

13条回答
  •  迷失自我
    2020-11-29 04:37

    CSS3 + jQuery Solution

    I wanted a solution that did NOT employ jQuery's fade effect as this causes lag in many mobile devices.

    Borrowing from Steve Fenton's answer I have adapted a version of this that fades the image in with the CSS3 transition property and opacity. This also takes into account the problem of browser caching, in which case the image will not show up using CSS.

    Here is my code and working fiddle:

    HTML

    
    

    CSS

    .fade-in-on-load {
        opacity: 0;
        will-change: transition;
        transition: opacity .09s ease-out;
    }
    

    jQuery Snippet

    $(".fade-in-on-load").each(function(){
        if (!this.complete) {
            $(this).bind("load", function () {
                $(this).css('opacity', '1');
            });
        } else {
            $(this).css('opacity', '1');
        }
    });
    

    What's happening here is the image (or any element) that you want to fade in when it loads will need to have the .fade-in-on-load class applied to it beforehand. This will assign it a 0 opacity and assign the transition effect, you can edit the fade speed to taste in the CSS.

    Then the JS will search each item that has the class and bind the load event to it. Once done, the opacity will be set to 1, and the image will fade in. If the image was already stored in the browser cache already, it will fade in immediately.

    Using this for a product listing page.

    This may not be the prettiest implementation but it does work well.

提交回复
热议问题