Javascript 如何使用height:auto获得元素的高度?
我尝试使用javscript将一个元素的高度设置为另一个元素的高度,我尝试使用jquery height方法,但它不起作用,因为其中一个元素的高度设置为自动:Javascript 如何使用height:auto获得元素的高度?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我尝试使用javscript将一个元素的高度设置为另一个元素的高度,我尝试使用jquery height方法,但它不起作用,因为其中一个元素的高度设置为自动: #content { background-color:#F2F2F2; width:1000px; margin:0px auto; text-align:left; min-height:900px; height:auto; border-top:5px solid #032F
#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;
}
那么,有没有简单的方法可以获取高度设置为“自动”的元素的高度?您可以使用getComputedStyle:
它应该返回元素的计算高度(以像素为单位)
有点像。您可以使用getComputedStyle:
它应该返回元素的计算高度(以像素为单位)
jQuery的.height方法仍然返回数值高度值,即使它被设置为自动。但一定要考虑到边距、填充和边框
我用你的CSS运行了一个测试,只是为了确保和.height可以正常工作。
jQuery有3个高度计算函数,它们以不同的方式考虑边距、填充和边框值
请审查:
$("#content").height()
$("#content").outerHeight()
$("#content").innerHeight()
jQuery的.height方法仍然返回数字高度值,即使它设置为自动。但一定要考虑到边距、填充和边框
我用你的CSS运行了一个测试,只是为了确保和.height可以正常工作。
jQuery有3个高度计算函数,它们以不同的方式考虑边距、填充和边框值
请审查:
$("#content").height()
$("#content").outerHeight()
$("#content").innerHeight()
只需使用此代码
$('#content').height();
只要使用这个代码
$('#content').height();
以下是我的代码示例:
$(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());
}
}
以下是我的代码示例:
$(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());
}
}
你说的是块本身的高度还是块内容的高度?你说的是块本身的高度还是块内容的高度?+1因为OP已经在使用jQuery,我认为这显然是一种非人为的获取高度的方法。确保你考虑了边距和边框,边距?你是说填充?修正了,全部3个。边距、填充和边框。唯一的问题是。。。我试着这样做:document.getElementById'content\u right'。innerHTML=$'content'。height;但它实际上并没有返回heights的值。。我发现我在加载页面之前调用了height,这就是为什么它返回null+1的原因,因为OP已经在使用jQuery,我认为这显然是一种非人为的获取高度的方法。请确保将边距和边框考虑在内,边距?你是说填充?修正了,全部3个。边距、填充和边框。唯一的问题是。。。我试着这样做:document.getElementById'content\u right'。innerHTML=$'content'。height;但它实际上并没有返回heights的值。。我发现我在加载页面之前调用了height,所以它返回null