加载嵌套图像后查找元素高度的一致方法 [英] Consistent way of finding element height after nested image has loaded
问题描述
我有一个 div.body
,其中包含 img
等几个元素。
I have a div.body
which contains an img
amongst a couple more elements.
我需要在 img
之后得到 div.body
的高度已加载。
I need to get the height of div.body
after img
has been loaded.
我目前正在使用以下方法进行衡量:
I'm currently using the following to measure:
var $body = $("div.body");
$body.find("img").ready(function(){
var bodyHeight = $body.outerHeight();
});
这会在90%的时间内返回正确的高度,但有时它返回的高度不包括图像的高度。
This returns the correct height 90% of the time, however some times it is returning the height not including the height of the image.
例如,如果 div.body中的其他元素
总计 50px
,我的图片高度 150px
,我需要得到 200px
,但有时这只会返回 50px
。
For example, if the other elements in div.body
sum up to 50px
, and my image has a height of 150px
, I need to get 200px
, however sometimes this is returning just 50px
.
这是为什么?不应该只在图像加载后调用 .ready()
函数吗?
Why is this? Shouldn't the .ready()
function only be called after the image has loaded?
我应该使用吗?一种不同的方法?
Should I be using a different method?
一旦图像可用,运行此代码的100%一致方式是什么?
What is a 100% consistent way of running this code once the image is available?
推荐答案
.ready()
在加载整个页面的DOM时运行。你想要 .load()
。
.ready()
runs when the entire page's DOM is loaded. You want .load()
.
参见讨论部分此处适用于动态添加内容的实现。
See the discussion section here for an implementation that works for dynamically added content.
这篇关于加载嵌套图像后查找元素高度的一致方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!