Consistent way of finding element height after nes

2019-08-13 18:38发布

I have a div.bodywhich contains an img amongst a couple more elements.

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();
});

This returns the correct height 90% of the time, however some times it is returning the height not including the height of the image.


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.


Why is this? Shouldn't the .ready() function only be called after the image has loaded?

Should I be using a different method?

What is a 100% consistent way of running this code once the image is available?

2条回答
对你真心纯属浪费
2楼-- · 2019-08-13 19:13

Per jQuery's documentation, there are a number of caveats for using the load event with images.

Take a look here:

jQuery event for images loaded

and here:

https://github.com/desandro/imagesloaded

查看更多
神经病院院长
3楼-- · 2019-08-13 19:16

.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.

查看更多
登录 后发表回答