I have a div with dynamic content (images and text). I then need to calculate the height of the div and do something to it.
However its currently calculating the height of the div BEFORE the contents have been added.
Does anyone have a solution to this?
$('#results').find('article').addClass(result); // add class to entire section
$('#results article').find('.details h1 span').html(title); // add title
$('#results article').find('.details p').html(message); // add message
var windowHeight = $('#results').find('article').innerHeight();
I have a div with dynamic content (images and text). I then need to calculate the height of the div and do something to it.
However its currently calculating the height of the div BEFORE the contents have been added.
Does anyone have a solution to this?
$('#results').find('article').addClass(result); // add class to entire section
$('#results article').find('.details h1 span').html(title); // add title
$('#results article').find('.details p').html(message); // add message
var windowHeight = $('#results').find('article').innerHeight();
Share
edited Sep 6, 2012 at 7:54
muudless
asked Sep 6, 2012 at 0:54
muudlessmuudless
7,5427 gold badges40 silver badges58 bronze badges
1
- 1 Does the content contain images? – Joseph Silber Commented Sep 6, 2012 at 0:56
3 Answers
Reset to default 7You probably have images in your content. You'll have to wait for them to load:
var $results = $('#results'),
$article = $results.find('article'),
deferreds = [];
$article.addClass(result); // add class to entire section
$article.find('.details h1 span').html(title); // add title
$article.find('.details p').html(message); // add message
$results.find('img').each(function()
{
var deferred = $.Deferred();
deferreds.push(deferred);
this.onload = function() { deferred.resolve(); }
});
$.when.apply($, deferreds).then(function()
{
var windowHeight = $article.innerHeight();
});
This method uses jQuery's Deferreds, which makes it super easy to track all the load
events.
If this isn't an issue with images that aren't yet loaded, then you may just need to trigger a layout yourself so you can get the desired dimensions.
The browser does not generally layout the new content until your script finishes (and it's sure that you are done changing the DOM). You can trigger a layout in your script by asking the DOM for a relevant dimension that the browser knows requires layout.
See this article http://gent.ilcore./2011/03/how-not-to-trigger-layout-in-webkit.html for a list of those properties that will trigger layout.
You can trigger the code to find height after all the dynamic data get loaded, using below code
$(window).load(function(){
var divHeight = $('#yourDivId').height()
}
Hope it will help
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745097909a4611092.html
评论列表(0条)