JQuery在图像上加载事件

我想在加载图像时将图像父级的大小调整为相同大小的图像。

这时我正在使用这段代码:

$(window).load(function(){ $('.image-principale').each(function(){ $(this).parent().css('height', $(this).height()); }); }); 

它工作,除了它只在每个图像加载时运行。 我试图直接为每个图像添加一个加载处理程序,但它们不会触发。

怎么了?

谢谢!

请尝试以下方法:

 ...Your HTML...  

请注意,脚本必须放在HTML之后,否则它将在元素存在之前运行,并且实际上不会执行任何操作。

您也可以尝试使用live ,如下所示:

 $('.image-principale').live('load', function(){ $(this).parent().css('height', $(this).height()); }); 

但是,我不知道它是否真的有效。

准备文件很容易:

 $(function() { $('.image-principale').load(function(){ $(this).parent().css('height', $(this).height()); }); }); 

甚至:

 $(function() { $('.image-principale').live('load', function(){ $(this).parent().css('height', $(this).height()); }); }); 

在外面或内部ready()

基本上,您希望从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 ){ }); 

我很确定这会解决你的问题。 我在这里发布,因为它可以帮助其他人。

适合我: http : //jsbin.com/ululo/edit

 $(function(){ $("img").load(function(){ $(this).parent().height( $(this).height() ); }); }); 

$(’img’)。每次图像resize时,加载似乎都会激活。 在我的情况下,它使我的网站变慢。 (我在FF上尝试过)