jQuery height() function returning inaccurate valu

2019-06-22 16:35发布

问题:

I'm using jQuery to measure the height of two divs (after document load) and then making the shorter div equal to the height of the taller div. However one of the div has an image in it, and it seems to be measure the height of the div as if the image isn't there (if I remove the image after everything has loaded, the height is accurate). Here is my code:

$(document).ready(function() {
    var rheight = $('#random').height();
    var qheight = $('#quote').height();
    if(rheight > qheight) $('#quote').height(rheight);
    else $('#random').height(qheight);
}

回答1:

If you know the height of the image in advance, you can set the image tag's height attribute. This will allow the browser to render the div at the correct height before the image loads, which means your height checks should work as expected.

Hooking the load event using jQuery can be problematic, according to its documentation. Apparently the event "can cease to fire for images that already live in the browser's cache".



回答2:

If you measure the <div> before the image has finished loading, its height won't be taken into account. You can wait for the image to be ready using a load event handler:

EDIT: The load event handler can be registered on the window object itself to avoid the reliability pitfalls pointed out by Chris:

$(window).load(function() {
    var rheight = $("#random").height();
    var qheight = $("#quote").height();
    if (qheight > rheight) {
        $("#quote").height(rheight);
    } else {
        $("#random").height(qheight);
    }
});


标签: jquery height