jQuery .height()和.outerHeight()返回零

时间:2013-08-07 15:51:34

标签: javascript jquery

我正在尝试编写一个小的jQuery插件,它会根据它的高度垂直居中div,

基本上在我的CSS中我有top: 50%,但由于高度是可变的,我需要计算它。

此HTML的内容类似于

<div class="button-wrapper js-center" data-center="vertical" style="margin-top: 0px;"
    <span class="sub-text">Multiline text with two lines</span>
    <a href="" class="shop-btn">Shop_</a>
</div>

在我的插件中,我尝试记录高度,但它一直返回零:

console.log($el);
console.log("$el.outerHeight(): " + $el.outerHeight());
console.log("$el[0].scrollHeight: " + $el[0].scrollHeight);

// output:
$el.outerHeight(): 0
$el[0].scrollHeight: 0 

当我使用开发工具进行检查时,它看起来像这样: enter image description here

所以我想知道可能出现什么问题,作为参考,这是我正在尝试写的插件:http://pastebin.com/Qz7BgkcG

编辑: 这是.button-wrapper

上使用的主要CSS
.button-wrapper {
    width: 250px;
    left: 50%;
    top: 50%;
    margin-left: -125px;
    position: absolute;
    z-index: 100; 
}

编辑2: 使用所有css重新创建,但我在这里没有遇到同样的问题:http://jsfiddle.net/8Etex/

1 个答案:

答案 0 :(得分:0)

我想知道问题是否因为jQuery的.height()方法返回元素的计算高度而不是实际的盒子模型(参考:API documentation)。

如果我查看您在上面的jsFiddle中创建的元素,您将看到Firefox无法识别绝对定位元素的计算高度。这意味着它将返回零。例如,如果我在CSS中的元素上强制使用height属性,则会更新计算的维度,并且我可以检索值。

Firefox Debugging Tools