How to change the CSS after image lazy loading (jQ

2019-07-25 10:03发布

问题:

I've got the following problem: after the user clicks on a thumbnail image, a bigger image is loaded with lazy loading and opens up. The code to load the bigger image is:

<img width="663" height="845" class="big" data-original="real/path/to/image" src="path/to/empty/small/picture">

When the user clicks on a thumbnail image, the following code is executed:

$("img.thumb").click(function() 
 {      
    var $cont = $(this).siblings('.item-content').children('.big'); 
    $cont.attr('src', $cont.attr("data-original"));
    setTimeout(function(){
        $cont.css({'height': 'auto', 'width': '100%'});
    }, 600);
 });

Each big image has to have the CSS "height" set to "auto", and the "width" set to "100%" because I am making a responsive/fluid layout. The above code gets its "src" attribute value from the "data-original" attribute. But "height: auto" and "width:100%" are set in this example to 600ms after the attributes do their replacing. This doesn't work, because I am using Isotope jQuery plugin (http://isotope.metafizzy.co/) for this and this plugin needs the real width and height of the element to position the grid properly. When "height: auto" and "width:100%" are set during the loading of an image, the plugin gets lost and makes positions the elements incorrectly.

So how do code this to set those 2 CSS properties after the image has loaded?

回答1:

You can use .load()

$('img.big').load(function() {
    if($(this).attr('src') == $(this).attr('data-original')) {
        $(this).css({'height': 'auto', 'width': '100%'});
    }
});

http://jsfiddle.net/TYufy/4/ - example using .load()



回答2:

Well, I found the solution: there is a small jQuery plugin, called imagesLoaded. It triggers a callback after all the selected child images have been loaded. The problem was that you can't do .load() on cached images.