Jquery偶尔会在图像上返回零高度和宽度
我正在观察一种不寻常的行为。 我有一个浮动的对话框,我正在放置一个图像。 我想使用jquery获取图像大小,并将其div容器调整为适当的大小。 它工作得相当好,但该function偶尔会返回零作为图像大小。
$('#dialogueContainer').html(''); var imageHeight = $('#lightImage').height(); var imageWidth = $('#lightImage').width(); console.log(imageHeight + 'x' + imageWidth); //<-- This occasionally returns "0x0"
我怀疑当jquery试图测量它的高度和宽度时,图像可能没有在DOM中准备好。 有什么想法吗?
你没错,图片没有加载。
最糟糕的是,在IE中,有时报告的大小类似于40×60(图像未加载时看到的小图标)。
jQuery报告load事件可以与图像一起使用: http : //api.jquery.com/load-event/
我很久以前试过解决这个问题,跨浏览器,我最终轮询图像大小以触发自定义“加载”事件。
谢谢
在将元素添加到DOM之前,可以将load
事件处理程序绑定到元素,以便在可用时获取宽度/高度。 您还可以使用CSS或内联属性明确设置图像的宽度/高度。
//create an img element, passing attribute values as we do, then bind an event handler to the `load` event for the image var $img = $('', { src : '/photos/' + file, id : 'lightImage' }).on('load', function () { //now that the image has loaded we can be sure the height/width values we receive are accurate var imageHeight = $(this).height(), imageWidth = $(this).width(); console.log(imageHeight + 'x' + imageWidth); }); //now change the HTML of the container, emptying the container, then appending a div element with the `dialogue` class which also has a child img element (our image from above) $('#dialogueContainer').html($('', { class : 'dialogue' }).html($img));
我喜欢在将元素添加到DOM或更改它的源之前将load
事件处理程序绑定到元素,这样您就知道在图像实际加载时(可以从缓存快速发生) load
事件就位。
请注意.on()
是jQuery 1.7中的新增内容,在这种情况下替换.bind()
(早期版本)。
更新
我想强调的是,如果你知道图像的尺寸,你应该明确地声明它们(这是更快的浏览器渲染的最佳实践):
我有这个问题试图获得包含段落的
的高度,这不是因为内容没有加载 – 我尝试在click
提醒它的高度,所以我可以肯定它是第一个并且是仍然得到0
返回。 事实certificate这是一个css
问题我使用clear
黑客添加了一个明确的类:
.clear { display:inline-block; } .clear:after, .container:after {content:"."; display:block; height:0; clear:both; visibility:hidden;} * html .clear { height:1%; } .clear { display:block; }
而这正好修正了它。
我相信你是对的。 尝试在加载图像后记录图像的宽度和高度:
var $img = $(''); $img.load(function(){ var imageHeight = $('#lightImage').height(); var imageWidth = $('#lightImage').width(); console.log(imageHeight + 'x' + imageWidth); }); $img.attr('src', '/photos/' + file);
注意我在将事件处理程序绑定到图像后设置了src
。 否则,我有不可预知的结果,具体取决于浏览器。
是否隐藏了图像display: none
或visibility: hidden
? 不可见元素的宽度和高度为0。