jquery: fade in image after image

為{幸葍}努か 提交于 2019-12-03 19:23:17

问题


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 displayed? and should I loop through the loaded images fadeIn and once fadedIn wait for the next to load?


回答1:


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

$('#some_image').hide()
    .load(function () {
      $(this).fadeIn();
    })
    .attr('src', 'images/headshot.jpg')



回答2:


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




回答3:


(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;
}


来源:https://stackoverflow.com/questions/1294513/jquery-fade-in-image-after-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!