jQuery获取响应图像的高度 [英] jQuery Get Height of Responsive Image
问题描述
我有一组响应页面的图像(即最大宽度设置为100%).
I have a set of images that are responsive to the page (i.e. max-width set to 100% ).
<div class="exh">
<img src="#" />
</div>
<div class="exh">
<img src="#" />
</div>
<div class="exh">
<img src="#" />
</div>
使用
.exh img {
max-width:100%;
}
在调整窗口大小后以及每次加载页面时,如何获取图像的高度?当我使用以下内容时,我得到的高度为0.
How do I retrieve the height of the image after the window is resized and whenever the page is loaded? When I use the following, I get a height of 0.
$(".exh img").each(function() {
var $this = $(this);
console.log( $this.height() );
});
推荐答案
对此问题,我提出了类似的问题:
per this answer I gave to a similar question :
为什么jQuery.css (宽度)在不同的浏览器中返回不同的值?
.width()
或height()
是元素的以DOM呈现"大小-并且要返回大于0的值,该元素需要DOM完全可用(即图像需要满载)
.width()
or height()
is the "rendered in the DOM" size of the element - and for it to return a value greater than 0, the element needs to be fully available to the DOM ( aka the image needs to be fully loaded )
您想要的是:
var myImage= new Image();
myImage.onload=function() { alert(this.height);}
myImage.src= "your/image/url";
简而言之-您需要在调用height()
In short - you need to guarantee that the image has loaded before you call height()
这篇关于jQuery获取响应图像的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!