Javascript Jquery偶尔会在图像上返回零高度和宽度

Javascript Jquery偶尔会在图像上返回零高度和宽度,javascript,jquery,Javascript,Jquery,我观察到一种不寻常的行为。我有一个浮动对话框,在其中我放置了一个图像。我想使用jquery获得图像大小,并将其div容器调整为适当的大小。它工作得相当好,但该函数偶尔会返回图像大小为零的值 $('#dialogueContainer').html('<div class="dialogue"><img src="/photos/' + file + '" id="lightImage" /></div>'); var imageHeight = $('#li

我观察到一种不寻常的行为。我有一个浮动对话框,在其中我放置了一个图像。我想使用jquery获得图像大小,并将其div容器调整为适当的大小。它工作得相当好,但该函数偶尔会返回图像大小为零的值

$('#dialogueContainer').html('<div class="dialogue"><img src="/photos/' + file + '" id="lightImage" /></div>');

var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();

console.log(imageHeight + 'x' + imageWidth); //<-- This occasionally returns "0x0"
$('#dialogueContainer').html('';
var imageHeight=$('#lightImage').height();
var imageWidth=$('#lightImage').width();

console.log(图像高度+x'+imageWidth)// 使用
显示:无
可见性:隐藏
是否隐藏过图像?不可见元素返回的宽度和高度为0。

您可以在将元素添加到DOM之前将
加载
事件处理程序绑定到元素,以在元素可用时获取宽度/高度。您还可以使用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 = $('<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($('<div />', { class : 'dialogue' }).html($img));

没错,图像没有加载

最糟糕的是,在IE中,有时报告的大小类似于40x60(图像尚未加载时看到的小图标)

jQuery报告加载事件可用于图像:

我很久以前就试图解决这个问题,跨浏览器,最后我轮询图像大小以触发自定义“加载”事件


谢谢

我相信你是对的。加载图像后,尝试记录图像的宽度和高度:

var $img = $('<img />');

$img.load(function(){
  var imageHeight = $('#lightImage').height();
  var imageWidth = $('#lightImage').width();

  console.log(imageHeight + 'x' + imageWidth);  
});

$img.attr('src', '/photos/' + file);
var$img=$('

请注意,在将事件处理程序绑定到图像后,我设置了
src
。否则,根据浏览器的不同,我会产生不可预测的结果。

我在尝试获取包含段落的
的高度时遇到了这个问题,这并不是因为内容没有加载-我尝试在
单击时提醒它的高度,所以我可以肯定它是第一个出现的,并且仍然得到
0
返回。结果是
css
问题。我使用
clear
hack向它添加了一个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; }

这就解决了问题。

由于图像尚未加载,您将获得0,您可以使用settimeout,如:

setTimeout(函数(){
//你的密码在这里
var imageHeight=$('#lightImage').height();
var imageWidth=$('#lightImage').width();

},2000);

此函数中较早的一行使容器div可见,因此它不应位于测量高度和宽度的点上。这正是我所需要的。我之前尝试过以不同的方式使用load,但显然我做得不对。谢谢。
.clear { display:inline-block; }   
.clear:after, .container:after {content:"."; display:block; height:0; clear:both; visibility:hidden;}
* html .clear { height:1%; }
.clear { display:block; }