javascript 获取 div 的高度并使用它设置另一个 div 的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11004498/
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 11:46:37  来源:igfitidea点击:

get height of a div and set the height of another div using it

javascript

提问by BrettAdamsGA

I have two divs, neither have a height set in css, as I want to take whatever height they end up as and set the other div to be that height.

我有两个 div,都没有在 css 中设置高度,因为我想采用它们最终的任何高度并将另一个 div 设置为该高度。

The javascript I have is this

我拥有的 javascript 是这个

function fixHeight() {
    var divh = document.getElementById('prCol1').height;
    document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';
    document.getElementById('prCol2').style.height = divh + 'px';
}

I have the following line of code just to see if I am getting some kind of actual response.

我有以下代码行只是为了看看我是否得到了某种实际响应。

document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';

I have a onload set to run the function

我有一个 onload 设置来运行该功能

my two divs look like this

我的两个 div 看起来像这样

<div id="prCol1">
     ..content..
</div>
<div id="prCol2" class="slideshow">
    ..content..
</div>

回答by Zoltan Toth

Use offsetHeight- http://jsfiddle.net/HwATE/

使用offsetHeight- http://jsfiddle.net/HwATE/

function fixHeight() {
    var divh = document.getElementById('prCol1').offsetHeight; /* change this */
    document.getElementById('prCol1').innerHTML = '<ul><li>' + divh + '</li></ul>';
    document.getElementById('prCol2').style.height = divh + 'px';
}

回答by Ryan

You can use jQuery to get the height and set it.

您可以使用 jQuery 获取高度并进行设置。

var h = $("#prCol1").height();
$("#prCol2").height(h);

回答by kevin cline

There are jQuery plugins to do this in a general way. Here's one.

有 jQuery 插件可以以一般方式执行此操作。 这是一个

回答by John Culviner

I would recommend using jQuery here. You can't get the height of an element like you are trying in any browser I know of. Here is the code if you use jQuery which is very straightforward. I wouldn't try to do this without jQuery because browsers can be different in respect to how you access height.

我建议在这里使用 jQuery。您无法像在我所知道的任何浏览器中一样尝试获取元素的高度。如果您使用 jQuery,这是非常简单的代码。我不会在没有 jQuery 的情况下尝试这样做,因为浏览器在访问高度的方式方面可能会有所不同。

function fixHeight() {
    var $prCol1 = $('#prCol1');
    var divh = $prCol1.height();
    $prCol1.html('<ul><li>' + divh + '</li></ul>');
    $('#prCol1').height(divh);
}