2012-02-25 98 views
0

我想通過使用javscript設置一個元素的高度爲另一個高度,我試過使用jquery height()方法,但它不工作,因爲其中一個元素的高度設置爲auto :如何獲得高度爲:auto的元素的高度?

#content 
{ 
    background-color:#F2F2F2; 
    width:1000px; 
    margin:0px auto; 
    text-align:left; 
    min-height:900px; 
    height:auto; 
    border-top:5px solid #032F76; 
    border-bottom:5px solid #032F76; 
    overflow:auto; 
} 

那麼有什麼簡單的方法來獲取高度設置爲自動的元素的高度?

+0

你是在談論塊本身的高度或其內容的高度? – 2012-02-25 22:35:38

回答

4

jQuery的.height()方法仍然返回數值高度值,即使它設置爲auto。但請確保您考慮保證金,填充和邊界。

我對CSS進行了測試,以確保和.height()正常工作。
http://jsfiddle.net/ysMge/8/

jQuery有3個高度計算功能,它們將邊距,填充和邊框值考慮到不同。

請查看:

$("#content").height() 
$("#content").outerHeight() 
$("#content").innerHeight() 

http://api.jquery.com/height/
http://api.jquery.com/outerHeight/
http://api.jquery.com/innerHeight/

+0

+1由於OP已經在使用jQuery,我認爲這將是一個明顯的非設計方法來獲得高度。 – hayavuk 2012-02-25 22:56:29

+0

「確保您考慮保證金和邊界」,保證金?你的意思是填充? – ajax333221 2012-02-25 23:08:46

+0

固定,全部3實際上。邊距,填充和邊界。 – Timeout 2012-02-25 23:20:50

1

您可以使用getComputedStyle

var elem = document.getElementById('content'); 
var height = window.getComputedStyle(elem,null).getPropertyValue('height'); 

應返回計算的高度,以像素爲單位的元素。

A有點contrived JS Fiddle example

0

只需使用此代碼

$('#content').height(); 
0

繼承人我的代碼示例:

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

function CenterFrameSizer(){ 
    // Sets the left box and the center box the same height. 
    if ($("#leftbox").height() > $("#contentbox").height()) { 
    $("#contentbox").height($("#leftbox").height()); 
    } else { 
    $("#leftbox").height($("#contentbox").height()); 
    } 
} 

function GalleryResize(){ 
    if ($("#leftbox").height() > $("#gallery").height()) { 
    $("#gallery").height($("#leftbox").height()); 
    } else { 
    $("#leftbox").height($("#gallery").height()); 
    } 
}