具有隐藏溢出子项的表格单元格的高度

时间:2017-11-06 19:57:02

标签: javascript jquery html css angularjs

我希望获得具有嵌套子项的表格单元格内容的实际高度,这些子项目可能包含溢出:隐藏样式,如下所示:

<tr>
    <td id="targetid">
        <div id="innertargetdiv">
            <div id="targetiddiv" style="overflow:hidden; max-height:50px;">
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
            </div>
        </div>
    </td>
    <td>Smith</td>
    <td>50</td>
  </tr>

JS代码:

console.log(document.getElementById("targetid").scrollHeight);
console.log(document.getElementById("innertargetdiv").scrollHeight);
console.log(document.getElementById("targetiddiv").scrollHeight);

输出: 51 50 100

如何从“#targetid”级别获得全高? 我不希望内容填满整个单元格,我只是想知道整个高度。 AngularJS / JQuery也是选项。

针对该问题可能的递归溶解:

var totalHeight: (any) => number = (e) => {
                var eHeight = 0;

                if (e.hasChildNodes()) {
                    eHeight = $.map(e.children, (child) => totalHeight(child))
                        .reduce((sum: number, value: number) => sum + value, 0);
                }

                //The height of the child elements might be smaller than the element with padding
                return Math.max.apply(Math, [eHeight, e.scrollHeight]);
            };

1 个答案:

答案 0 :(得分:1)

根据您的评论,这是克隆元素的示例。

&#13;
&#13;
const targetElm = document.getElementById('targetid')
const clonedElm = document.createElement('div')

clonedElm.setAttribute('id', 'clonedTarget')
clonedElm.style.visibility = 'hidden'
clonedElm.innerHTML = targetElm.innerHTML.replace(/target/g, 'clone')   	

const body = document.getElementsByTagName('body')[0]
body.append(clonedElm)
document.getElementById('cloneiddiv').style = ''

const height = document.getElementById('innerclonediv').scrollHeight
document.getElementById('clonedTarget').remove()

console.log(height)
&#13;
<table>
 <tr>
    <td id="targetid">
        <div id="innertargetdiv">
            <div id="targetiddiv" style="overflow:hidden; max-height:50px;">
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
                Thiscell<br>
            </div>
        </div>
    </td>
    <td>Smith</td>
    <td>50</td>
  </tr>
 </table>
&#13;
&#13;
&#13;