加载图像时,我想将图像父级的大小调整为与图像相同的大小。
此时我正在使用此代码:
$(window).load(function(){
$('.image-principale').each(function(){
$(this).parent().css('height', $(this).height());
});
});
它工作,除了它只在每个图像都加载时运行。我试图直接为每个图像添加一个负载处理程序,但它们没有触发。
怎么了?
谢谢!
尝试以下操作:
...Your HTML...
<script type="text/javascript">
$('.image-principale').load(function(){
$(this).parent().css('height', $(this).height());
});
</script>
请注意,脚本必须放在 HTML 之后,否则它将在<img>
元素存在之前运行并且实际上不会做任何事情。
您也可以尝试使用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 ){ });
我很确定这将解决您的(非常老的......对不起)问题。我把它贴在这里,因为它可以帮助其他人。
每次调整图像大小时,$('img').load 似乎都会触发。就我而言,它使我的网站变慢。(我在FF上试过)
为我工作:http: //jsbin.com/ululo/edit
$(function(){
$("img").load(function(){
$(this).parent().height( $(this).height() );
});
});