简体   繁体   English

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

[英]Jquery occasionally returns zero height and width on image

I am observing an unusual behavior. 我观察到一种不寻常的行为。 I have a floating dialogue box in which I am placing an image. 我有一个浮动的对话框,我在其中放置一个图像。 I want to get the image size using jquery and resize its div container to the appropriate size. 我想使用jquery获取图像大小,并将其div容器调整为适当的大小。 It works fairly well, but the function occasionally returns zeros as the image sizes. 它运行得相当好,但该功能偶尔会返回零作为图像大小。

$('#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"

I suspect that the image may not be ready in the DOM when jquery attempts to measure its height and width. 我怀疑当jquery试图测量它的高度和宽度时,图像可能没有在DOM中准备好。 Any thoughts? 有什么想法吗?

You can bind a load event handler to the element before adding it to the DOM, to get the width/height once it's available. 在将元素添加到DOM之前,可以将load事件处理程序绑定到元素,以便在可用时获取宽度/高度。 You can also explicitely set the width/height of the image using CSS or inline attributes. 您还可以使用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));

I like to bind the load event handler to the element before adding it to the DOM or changing it's source, this way you know the load event is in place when the image actually loads (which can happen quickly from cache). 我喜欢在将元素添加到DOM或更改它的源之前将load事件处理程序绑定到元素,这样您就知道在图像实际加载时(可以从缓存快速发生) load事件就位。

Note that .on() is new in jQuery 1.7 and in this case replaces .bind() (of earlier versions). 请注意.on()是jQuery 1.7中的新增内容,在这种情况下替换.bind() (早期版本)。

Update 更新

I would like to stress the fact that if you know the dimensions of your image you should explicitly declare them (this is best practice for faster browser rendering): 我想强调的是,如果您知道图像的尺寸,则应明确声明它们(这是更快的浏览器渲染的最佳实践):

<img width="100px" height="200px" src="..." />

You're right, the image is not loaded. 你没错,图片没有加载。

Worst, in IE, sometimes the size reported is something like 40x60 (the small icon you see when the image is not loaded yet). 最糟糕的是,在IE中,有时报告的大小类似于40x60(图像未加载时看到的小图标)。

jQuery reports that the load event can be used with images: http://api.jquery.com/load-event/ jQuery报告load事件可以与图像一起使用: http//api.jquery.com/load-event/

I tried a long time ago to solve this problem, cross browser, and I ended up polling the image sizes to trigger a custom "load" event. 我很久以前试过解决这个问题,跨浏览器,我最终轮询图像大小以触发自定义“加载”事件。

Thanks 谢谢

I had this problem trying to get the height of a <div> containing paragraphs and it wasn't because the content hadn't loaded - I tried alerting the height of it on a click so I could be sure it was there 1st and was still getting 0 returned. 我有这个问题试图获得包含段落的<div>的高度,这不是因为内容没有加载 - 我尝试在click提醒它的高度,所以我可以肯定它是第一个并且是仍然得到0返回。 It turned out to be a css issue I added a clear class to it using the clear hack: 事实证明这是一个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; }

And that fixed it right up. 这就解决了这个问题。

I believe you are right. 我相信你是对的。 Try logging the image's width and height once the image has loaded: 尝试在加载图像后记录图像的宽度和高度:

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

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

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

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

Notice I've set src after binding the event handler to the image. 注意我在将事件处理程序绑定到图像后设置了src Otherwise, I had unpredictable results, depending on the browser. 否则,我有不可预知的结果,具体取决于浏览器。

Is the image ever hidden, either with display: none or visibility: hidden ? 是否隐藏了图像display: nonevisibility: hidden Invisible elements return a width and height of 0. 不可见元素的宽度和高度为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM