span标记上的jquery .height()和.width()会得到不一致的结果

ben*_*ben 2 html jquery height width

我需要获取变量高度和宽度元素#sentence的尺寸,以便更改与其相关的其他元素的尺寸.#sentence在浏览器窗口中居中,无论其内容如何,​​都确定其高度和宽度.我的代码看起来像这样:

HTML

<body>
    <div id="wrapper">
        <div id="cell">
            <span id="sentence">
                sentence
            </span>
        </div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

JS

$(document).ready(function(){
    var h = $("#sentence").height();
    alert(h);
});
Run Code Online (Sandbox Code Playgroud)

当我尝试获取.height().width()#sentence,我回来不一致的值.通常对于28的高度,但有时它会回到19.对于宽度,我得到84或有时52.

我想也许差异是由于滚动条暂时出现然后在页面加载时消失.我尝试添加overflow: hidden;htmlbody摆脱可能被显示出来任何滚动的,但没有奏效.我也尝试过添加

$(window).resize(function(){ 
    h = $("sentence").width(); 
});
Run Code Online (Sandbox Code Playgroud)

那没用.使用.css("height")似乎也不起作用.

那会是什么?我为什么遇到这个问题?在此先感谢您的帮助.

Mic*_*ade 6

为了使尺寸更正,浏览器需要布置并呈现页面..ready(...)触发事件时不一定如此.

请尝试使用$(window).load(...).