Calculating height using jQuery differs in Firefox

2020-07-14 09:17发布

问题:

I have a question that was already asked here, but the solution offered there did not work. The problem is that I'm using the jQuery height() function to return the height of a div. It works nicely in Firefox, but returns a value that is 300px smaller in Chrome...

You can see an example of this bug here. Though I must say it's in Hebrew. Though that shouldn't matter much...

Has anyone had that happen before? Here's the code that calculates the height:

var heightLeftCol = $('#leftCol').height();
var sidebarHeight = $('#sidebar').height();
var minHeight = heightLeftCol > sidebarHeight ? heightLeftCol : sidebarHeight; 
$('#postArea').css('min-height', minHeight+100);

EDIT: This problem was not fixed but worked around in a way that I don't like, but it'll do for now. Here's the "solution" that I came up with:

if (jQuery.browser.safari) {
    $('#postArea').css('min-height', minHeight+400 + 'px');
}
else {
    $('#postArea').css('min-height', minHeight+100 + 'px');
}

Since both Safari and Chrome run on WebKit, the browser.safari actually selects chrome as well..I definitely do not consider this an optimal solution.

Thanks! Amit

回答1:

In Chrome, the height of the div does not include the height of your 300-pixel tall image "sheli.jpg" because it isn't specified anywhere in the html or css. If you specify the height="300" in your <img> tag or height: 300px; as part its style, it will work.



回答2:

If is because your image at that time is not yet loaded, therefore the height is 0. That explains the height deficit you got in Chrome. To solve this problem, put the piece of code that set the height inside jQuery(window).load() like this:

jQuery(window).load(function(){
     jQuery("#div1").css("height", jQuery("#div2").height());
});


回答3:

Per the discussion Justin and I had in the comments above wrapping the jQuery code in $(window).load() will allow this code to execute properly after the images have loaded completely.