2013-11-22 135 views
1

這是一個愚蠢的問題,但我似乎無法弄清楚。基本上我想要我的div元素的高度。但一些它如何保持返回0.當我檢查Chrome中的元素時,它給了我一個高度。代碼:無法獲得div元素的高度

HTML

<div id="signup"> 
       <div class="panel"> 
       </div> 
</div> 

CSS:

.panel 
{ 
    width: 90%; 
    -webkit-border-radius: 10px; 
    -moz-border-radius: 10px; 
    -ms-border-radius: 10px; 
    -o-border-radius: 10px; 
    border-radius: 10px; 
    background: #0071bc; 
    padding: 1em; 
    border: 0.3em solid; 
    border-color: #073b73; 
    color: #ffffff; 
    position: relative; 
    left:0; 
    right: 0; 
    margin: auto; 

} 

JQuery的:

alert($("#signup .panel").outerHeight()); 
alert($("#signup .panel").height()); 

我在下面的方法使用上述線路:

$(document).ready(function(){ 
}); 

$(window).load(function(){ 
}); 

每次我試圖提醒身高,我只是繼續得到0.我注意到,在CSS中,如果指定高度,即height:361px;height:40%;我得到361或40.但我不想要這個。我的面板高度根據其中的元素進行更改。一旦渲染完成,我希望登錄的高度。我現在試過...我不知道如何做到這一點。請幫忙。

+1

你是否包括jQuery的?它在[小提琴](http://jsfiddle.net/mathieujonson/Sryzk/)中工作。注意:'console.log()'比'alert()'好。它不那麼討厭。 –

回答

3

爲什麼高度返​​回爲 「0」,沒有數據:

這似乎是我的權利。 height()返回沒有填充和邊距的高度。

鉻原因顯示的高度是因爲你有填充和邊框:而且因爲元素沒有內容(數據)爲什麼它的工作原理與outerHeight高度返回0。

。這就是爲什麼你會得到outerheight()的價值。 OuterHeight()將返回填充和邊框的高度。如果您使用outerHeight(true),您將獲得元素的高度加上填充,邊框和邊距。

注:

如果你想要一個元素的高度包括填充而不是邊界。您將使用innerHeight()。和innerHeight(true)如果你想填充和邊緣高度沒有邊框高度。

Documentation

+0

是的。 outerHeight()將顯示填充和邊框的空div的高度) –

+0

雖然OP獲得0高度不是OP嗎?他說,他*沒有得到0的唯一時間是當他明確設定div的高度時。 –

+0

當我在小提琴中運行他的代碼時,我得到了「40」作爲outerHeight的值。 http://jsfiddle.net/YZATJ/1/這是因爲他已經定義了填充和邊框。 –

0

的代碼是作品,如本fiddle。如果代碼不起作用,問題就在別處。確保jQuery已鏈接,並且控制檯中沒有錯誤。

小提琴HTML:

<div id="signup"> 
    <div class="panel"> 
    Tons of Content<br> 
    Even More Content 
    </div> 
</div> 

小提琴的jQuery:

$(document).ready(function(){ 
    console.log($("#signup .panel").height()); 
});