jquery: fade in image after image

前端 未结 3 2037
青春惊慌失措
青春惊慌失措 2020-12-30 15:28

I have a page with 10 images in and I want to fade them in one after another once the image has been downloaded. how can I detect the image is loaded and ready to be display

相关标签:
3条回答
  • 2020-12-30 16:19

    Just use the load() event on an image. E.g.

    $('#some_image').hide()
        .load(function () {
          $(this).fadeIn();
        })
        .attr('src', 'images/headshot.jpg')
    
    0 讨论(0)
  • 2020-12-30 16:28

    (Based on Kris Erickson's answer)

    You may be able to avoid potential race conditions by adding the event to the image before adding it to the DOM (unconfirmed but I like to play it safe). Also this method is good for fading images on top of each other.

    This is what I'm using for a gallery control where I add an image on top of another image and fade it in - then I remove the bottom image if I've already added 2 images.

    var url = .....;
    var container = $('#images_container');
    
    $("<img />").hide().load(function () {
        $(this).fadeIn(); 
    }).attr('src', url).appendTo($(container ));
    
    if ($(container).children().length > 2) {
        $(":nth-child(1)", container).remove();
    }
    

    Here's the HTML:

    <div id="images_container"></div>
    

    The CSS must be set up like this or the images will stack instead of being on top of each other.

    #images_container {
       position: relative;
    }
    
    #images_container {
       position: absolute;
    }
    
    0 讨论(0)
  • 2020-12-30 16:29

    You can preload the images maybe (See here) and then call the the fadein and fadeout methods sequentially in a loop.

    0 讨论(0)
提交回复
热议问题