jquery .height() and .width() on span tag gets inc

2019-07-21 00:46发布

问题:

I need to get the dimensions of a variable-height-and-width element, #sentence, in order to change the dimensions of other elements that are related to it. #sentence is centered in the browser window, and its height and width are determined whatever its contents are. My code looks like this:

HTML

<body>
    <div id="wrapper">
        <div id="cell">
            <span id="sentence">
                sentence
            </span>
        </div>
    </div>
</body>

CSS

body, html  {
    font-size: 18pt;
    padding: 0px;
    margin: 0px;
    overflow: hidden;
}
#wrapper    {
    width: 100%;
    height: 100%;
    display: table;
    text-align: center;
}
#cell   {
    display: table-cell; vertical-align: middle;
}

#sentence   {
    display: inline-block;
    background-color: #abc;
    padding: 1em;
}

JS

$(document).ready(function(){
    var h = $("#sentence").height();
    alert(h);
});

When I try to get the .height() or .width() of #sentence, I get back inconsistent values. Usually for the height it's 28, but sometimes it comes back as 19. For the width, I get 84 or sometimes 52.

I thought that perhaps the difference was caused by scrollbars temporarily appearing and then disappearing when the page loads. I tried adding overflow: hidden; to html and body to get rid of any scrollbars that might be showing up, but that didn't work. I also tried adding

$(window).resize(function(){ 
    h = $("sentence").width(); 
});

That didn't work. Using .css("height") doesn't seem to work either.

So what will? Why am I having this problem? Thanks in advance for any help with this.

回答1:

For the dimensions to be correct the browser needs to have layed out and rendered the page. This isn't necessarily true when the .ready(...) event is fired.

Try using $(window).load(...) instead.