javascript 如何动态获取div的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8744837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:27:34  来源:igfitidea点击:

How to get the height of the div dynamically

javascriptjqueryhtml

提问by Abbas

i have 2 div's, left and right, the content in right div is setted dynamically so as its height, so i haven't specified its height in html, now what i want is the height of the left div should be equal to the right div, how to set the height of the left div as per the height of right div, using jquery, i tried

我有2个div,左右,右边div中的内容是动态设置的,所以我没有在html中指定它的高度,现在我想要的是左边div的高度应该等于右边div,如何根据右div的高度设置左div的高度,使用jquery,我试过了

$("#leftDiv").height($("RightDiv").height());

this does not seems working, as i haven't specified the height of the right div in html. is there any other wayout, apart from using tables.

这似乎不起作用,因为我没有在 html 中指定正确 div 的高度。除了使用表格之外,还有其他出路吗?

采纳答案by dknaack

Description

描述

Looks like your selector for RightDivis not right or you forgot to wait while the DOM is loaded.

看起来您的选择器RightDiv不正确,或者您忘记等待加载 DOM。

Sample

样本

Html

html

<div id="leftDiv" style="border:1px solid red">left div</div>
<div id="RightDiv" style="height:100px; border:1px solid red">right div</div>

jQuery

jQuery

$(function() {
   $("#leftDiv").height($("#RightDiv").height());
})

More Information

更多信息

回答by Alex Dn

Try this:

试试这个:

$("#leftDiv").height($("#RightDiv").get(0).scrollHeight);

回答by Aram Mkrtchyan

$(function() {
 if($("#RightDiv").height() > $("#leftDiv").height()){    
           $("#leftDiv").css("height", $("#RightDiv").height() + "px");
        } else {
           $("#rightDiv").css("height", $("#leftDiv").height() + "px");
       }
}

回答by Teun Pronk

try

尝试

var firstHeight = $("#RightDiv").height() + 'px';
$("#leftDiv").css("height", firstHeight);