2012-02-25 89 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()); 
    } 
}