Consistent way of finding element height after nested image has loaded

岁酱吖の 提交于 2020-01-05 07:55:41

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/13489883/consistent-way-of-finding-element-height-after-nested-image-has-loaded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!