获取要复制的子元素的总高度

Get total height of child elements to duplicate

本文关键字:高度 元素 复制 获取      更新时间:2023-09-26

我有一个固定的位置#header,其中包含.child元素的X,高度为19px,隐藏溢出。#header有一个:hover,它将高度更改为max-height(因此它扩展了其中的.child元素)和一个动画transition: max-height 0.2s 1s ease;。(固定div不能操纵div左右,因为它的增长或缩小),所以我想使position: relativediv低于#header,具有相同的内容高度#header的增长或缩小与#header:hover相同的时间,但可以移动其他div低于它的动画。

我在Stackoverflow上的其他帖子上找到了一种方法,它几乎做到了JSFIDDLE的技巧,除了它将.child元素的所有高度计算在一起。我只需要#parent的高度,但这是max-height的高度,而不是固定的高度。

[update] SOLVED thanks to @joel-almeida因为div有一个很短的高度和隐藏溢出,它不能读取div的高度,但添加了。scrollheight后,它可以读取div的高度,无论它是可见的还是隐藏的

当你可以直接得到父高度时,为什么要计算所有子高度?

Try this:

$(function(){
    var totalHeight = 0;
    totalHeight = $('#parent')[0].scrollHeight;
    alert("Total height of all divs: " + totalHeight);
    $(".clonechild").height(totalHeight);
});
#parent {
    float: left;
    width: 500px;
    background-color: #e0e0e0;
}
#parent .child {
    float:left;
    height:100px;
    width:100px;
    background-color:#666;
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    border: 1px solid black;	
}
#parent .child , .clonechild p {
    font-size: 14px;
    color: #fff;
    text-align: center;
}
        #cloneparent {
            position: absolute;
            margin: 300px auto auto 0px;
            width: 510px;
            background-color: #e0e0e0;
        }
        #cloneparent .clonechild {
            float:left;
            min-height:100px;
            height: ;
            width:100px;
            background-color:#666;
            box-sizing:border-box;
            -moz-box-sizing:border-box;
            -webkit-box-sizing:border-box;
            border: 1px solid black;   
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
    <div class="child"><p>1</p></div>
    <div class="child"><p>2</p></div>
    <div class="child"><p>3</p></div>
    <div class="child"><p>4</p></div>
    <div class="child"><p>5</p></div>
    <div class="child"><p>6</p></div>
    <div class="child"><p>7</p></div>
    <div class="child"><p>8</p></div>
</div>
<p>__#parent clearly not 800px height</p>
<div id="cloneparent">
    <div class="clonechild"><p>this needs to be the same height as #parent</p></div>
    <p>__#cloneparent clearly not same height as #parent</p>
</div>