简体   繁体   中英

Jquery show preloader for every image?

I've a website with a lot of images:

<img class='thumb' src=thumbs/image1.jpg/>
<img class='thumb' src=thumbs/image2.jpg/>
<img class='thumb' src=thumbs/image3.jpg/>
<img class='thumb' src=thumbs/image4.jpg/>

I wonder if I can display a loading-div for every single image and when it's loaded the div hides? I'm using jquery for most of my animations. Can i solve that with jquery.

It would be cool if every image shows this loading-div centered in the middle of the image. When the image is loaded the div should hide!

Is that possible? Thank you for your help!

Something like this should do it:

$("img.thumb").after('<img class="spinner" scr="spinner.gif"/>');
$("img.thumb").load(function() {
    $(this).next(".spinner").remove();
}).each(function() {

    // if the images is loaded from cache, trigger the load event
    if(this.complete) $(this).trigger('load');
});

But as others have commented, spinners all over the page will probably look horrible.

http://api.jquery.com/load-event/

Would it not be easier to do it in CSS?

.thumb {
    background: url(spinner.gif) center center;
}

When the image has loaded it'll hide the background image.
Note : You may need to give it a width and height, which shouldn't be a problem if they're all thumbnails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM