开发者

Changing img src with javascript/jquery

I want to change the source of an image and show a "Loading..." image while the target image is loading. I am doing the following:

$('#imageid').attr('src','loading.jpg');
$('#imageid').attr('src',path);

where path is the path of the target image. However, JQuery is carrying out both actions at once, and loading.jpg is never displayed. The same thing happen开发者_Python百科s when using regular Javascript.

How can I make the first line take effect so that loading.jpg is displayed while the next image loads?


The issue is, jQuery is, in fact, changing the src on the image, and there's no simple way to complete the task as you have above (if you want the image to be loading, you'll need to have that be the src of the img tag, but therefore that src cannot also being loading.gif). You can however accomplish this through a little Javascript and CSS:

 $('#imageid').attr('src', path).addClass('loading').load(function() { $(this).removeClass('loading'); })

Then simply add a CSS style to put a loading image over the image item when it has a loading class attached.

 img.loading { 
   background: url("/loading.gif") no-repeat center center transparent;
 }

This should make a smooth loading for your image. It's worth noting you could also do this using two img tags and swapping which one is visible. Also, be careful with the load handler, as cached images will load instantly in certain browsers. Enjoy!


Since you are replacing the image src one after the other it is not visible may be before the first image is loaded the next image source request takes place. You can try to set the next image after the first image is completely loaded. This can be achieved by set the next image source in the image load event. Try this

$('#imageid').load(function(){
   $(this).unbind('load')//We need to unbind the load event because load event will again get called next time when we set the source of this image

   $(this).attr('src',path);
}).attr('src','loading.jpg');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜