开发者

jQuery - Ability to Change an IMG Source, and show a loader until the image is loaded by the browser

I have a frame with an image tag inside, like a photo gallery

<div id="frame">
 <img src="yahoo.com/logo.gif" id="photo" />
</div>

With jQuery I'm going to dynamically change the img src to a different image URL. This causes the frame to jump in height as the image dimensions are different. It also cause开发者_StackOverflow社区 a flash as the browser loads the image. It's a bad experience.

What'd I'd like to know if is possible, is whenever the img src is changed, is for jQuery to show a default loader, and then once the image is fully loaded, then show the image and remove the loader.

Any suggestions? hopefully a plugin? thanks


You could try something like this:

$('#frame > img').after('<img src="loading.jpg" />') // some preloaded "loading" image
                 .hide()
                 .attr('src','/some/new/value.jpg')
                 .one('load', function() {
                    $(this).fadeIn().next().remove();
                 });
  • the after()(docs) method to insert a "loading" image (should be preloaded)
  • the hide()(docs) method to hide the current image
  • the attr()(docs) method to change the src
  • the one()(docs) method to bind a load event that will be removed once the image is loaded
  • the fadeIn()(docs) method to give a nice fade in effect once the image has loaded
  • the next()(docs) method to get to the "loading" image
  • the remove()(docs) method to remove the "loading" image


You could probably preload the images, as described here: Preloading images with jQuery

If you don't want your frame div to jump in height, you will need to set a fix height on the div that will fit all image sizes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜