基本上,您想监听来自 img 元素的 load 或 readystatechange 事件。
所以你需要这样做:
$(window).load(function(){
$('.image-principale img').on("load readystatechange", function(){
// Here you can check whether it state complete by checking
// if(this.complete || (this.readyState == 'complete' && e.type == 'readystatechange') ) { }
$(this).parent().css('height', $(this).height());
});
});
但是...这种方式有一些(大)警告。即它不会“总是”工作,它不会与“缓存”图像一起工作(有时)。
最好的方法实际上是从 Desandro,一个名为 jquery.imagesLoaded
它将检查加载事件和其他一些条件(如损坏的图像、缓存的图像、加载的元素……),并在加载所有元素时为您提供反馈。
用法是(你可以在网站上看到更多):
// Loading script
var dfd = $('#my-container').imagesLoaded(function($images, $proper, $broken){
//Here you can do a loop on $proper that is the list of images that properly loaded.
}); // save a deferred object and use dfd later
您还可以为每个加载的图像设置一个回调:
dfd.progress(function( isBroken, $images, $proper, $broken ){ });
我很确定这会解决您的(非常老的……抱歉)问题。我在这里发布它是因为它可以帮助其他人。