outerHeight(true) gives wrong value

前端 未结 10 1478
旧时难觅i
旧时难觅i 2021-01-07 18:21

I want the height of a container element, including margins and paddings.

When I hover over the element in Chrome development tool, I get the value that I\'m lookin

相关标签:
10条回答
  • 2021-01-07 18:38

    I've run into same problem.

    Firefox outerheight via console.log: 430 Chrome outerheight via console.log: 477

    Real outerheight (firebug layout): 820

    After opening Firebug or removing statusbar it sets correct value (820) in console.log (and hence the code works as it should).

    The issue was due to images. Even though you are running it on document ready, not all images might be loaded yet, and therefore the calculations are wrong.

    I am using desandro's plugin and it has fixed my issue. https://github.com/desandro/imagesloaded

    0 讨论(0)
  • 2021-01-07 18:38

    I think you might need

    .outerHeight({margin: true});
    

    As per here:

    The margin can be included by passing an options map with margin set to true.

    0 讨论(0)
  • 2021-01-07 18:40

    I had the same problem. I get the correct height in Chrome by using setTimeout to wait a bit:

        setTimeout ( function () {
            var ht = $('.my-class').outerHeight( true );
        }, 1);
    

    I hope that helps!

    0 讨论(0)
  • 2021-01-07 18:45

    I have experience this issue several times, and the best solution, without the use of any plugins or unruly setTimeout functions, is to use hook into the browser's onLoad event. With jQuery, it's done like so:

    $(window).load(function(){ ...outerHeight logic goes here... });

    This could be totally separate from your standard $(function(){ ...code... }); so all of your other properly working code doesn't have to wait until every single element on the page has loaded.

    Why this happens in the first place:
    Chrome has a different rendering algorithm than Firefox, which causes it to trigger the onLoad event before all the elements on the page are completely drawn/displayed and available for jQuery to select and retrieve heights. setTimeout() will work most of the time, but you don't want to develop a dependency on something so blind by nature – who knows, in the future this "quirk" in Chrome could be fixed! :)

    0 讨论(0)
提交回复
热议问题