使用一个div的高度来设置另一个div的高度

7

我有两个div,没有在css中设置高度,因为我想取得它们最终的高度并将另一个div设置为相同的高度。

我的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';
}

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

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

我将为你翻译以下内容:

我已经设置了onload来运行该函数

我的两个div看起来像这样

<div id="prCol1">
     ..content..
</div>
<div id="prCol2" class="slideshow">
    ..content..
</div>
5个回答

11

使用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';
}

我不相信offsetHeight在所有浏览器中都得到了完全支持。我还没有对是否jQuery修复了这些问题进行深入研究,但这正是它的目的,对吧?http://vadikom.com/dailies/offsetwidth-offsetheight-useless-in-ie9-firefox4/ - John Culviner
@JohnCulviner 是的,这可能会导致 1px 的差异,但在 OP 的情况下,我认为这并不是真正相关的。他的目标是使两个 <div> 高度相等,而且确实会发生这种情况。我认为这种在 IE9 中可能出现的 1px 差异(甚至可能不会出现)是不包含 40K 库(如果尚未包含)的一个很好的权衡。原始 JS 总是更快的... 而且 offsetHeight 在每个浏览器中都受支持 - http://www.quirksmode.org/dom/w3c_cssom.html - Zoltan Toth

2

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

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

2

您可以通过以下代码获取高度:

document.getElementById('YourElementID').clientHeight;

0

0
我建议在这里使用jQuery。在我所知道的任何浏览器中,您都无法像您尝试的那样获取元素的高度。如果您使用非常简单的jQuery,则可以使用以下代码。我不会尝试在没有jQuery的情况下执行此操作,因为浏览器在访问高度方面可能会有所不同。
function fixHeight() {
    var $prCol1 = $('#prCol1');
    var divh = $prCol1.height();
    $prCol1.html('<ul><li>' + divh + '</li></ul>');
    $('#prCol1').height(divh);
}

请快速查看我的 jsfiddle,先生;-) - Zoltan Toth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接