javascript Jquery 偶尔会在图像上返回零高度和宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9235413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery occasionally returns zero height and width on image
提问by Tanoro
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. It works fairly well, but the function occasionally returns zeros as the image sizes.
我正在观察一种不寻常的行为。我有一个浮动对话框,我在其中放置图像。我想使用 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"
I suspect that the image may not be ready in the DOM when jquery attempts to measure its height and width. Any thoughts?
我怀疑当 jquery 尝试测量其高度和宽度时,该图像可能未在 DOM 中准备好。有什么想法吗?
采纳答案by Mike Gleason jr Couturier
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 报告加载事件可以用于图像: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
谢谢
回答by Jasper
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. You can also explicitely set the width/height of the image using CSS or inline attributes.
您可以load
在将元素添加到 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));
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).
我喜欢在将load
事件处理程序添加到 DOM 或更改其源之前将事件处理程序绑定到元素,这样您就知道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="..." />
回答by Rob
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. It turned out to be a css
issue I added a clear class to it using the clear
hack:
我在尝试获取<div>
包含段落的高度时遇到了这个问题,这不是因为内容没有加载 - 我尝试在 a 上提醒它的高度,click
这样我就可以确定它在第 1 个并且仍然被0
返回。结果证明这是一个css
问题,我使用clear
hack向它添加了一个明确的类:
.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.
就这样解决了。
回答by osahyoun
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. Otherwise, I had unpredictable results, depending on the browser.
请注意,我在将src
事件处理程序绑定到图像后进行了设置。否则,我会得到不可预测的结果,具体取决于浏览器。
回答by Joe
Is the image ever hidden, either with display: none
or visibility: hidden
? Invisible elements return a width and height of 0.
图像是否曾经隐藏,无论是display: none
还是visibility: hidden
?不可见元素返回 0 的宽度和高度。
回答by Aniket
You are getting 0 becuase image is not loaded yet , you can use settimeout like:
你得到 0 因为图像还没有加载,你可以使用 settimeout 像:
setTimeout(function () {
// your code goes here
var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();
},2000);
setTimeout(function () {
// your code goes here
var imageHeight = $('#lightImage').height();
var imageWidth = $('#lightImage').width();
},2000);