繁体   English   中英

如何获取内部 HTML 内容高度

[英]How to get inner HTML content height

我想通过 JavaScript 获取内部 html 高度。 假设我有

<div>Content</div>

如果 div 字体大小增加或嵌套在父级中的多个 div,我如何获得父级 div 的高度?

编辑:即使嵌套的 div 也有边框和填充。

如果它必须在 vanilla JS 中......

var height = document.getElementById('content').clientHeight;

这将不包括元素中的任何边框或滚动条,只是填充。 如果要包含边框和滚动条,可以改用offsetHeight

如果父元素的高度为0 ,并且您想要其中内容的高度(这是我认为 OP 要求的),则接受的答案是不正确的。 在这种情况下, scrollHeight是您想要的属性。

const divInnerContentHeight = document.querySelector('div').scrollHeight;

使用clientHeightoffsetHeight将返回0

使用 clientHeight 和 getElementsByTagName div 来获取特定的 div 高度

document.getElementsByTagName('div')[0].clientHeight

http://codepen.io/nagasai/pen/XKoxZw

像这样的东西?

<div id="MyDiv">Content</div>

console.log(document.getElementById("MyDiv").offsetHeight);

在高度计算中包括填充和边框:

document.getElementById('myDiv').offsetHeight;
 //We can do his using JQuery

    //Returns the element's height
    $('#content').height();
   // Returns the height with padding
    $('#content').innerHeight();
   // Returns the height with padding and border
    $('#content').outerHeight();
   // Returns the height with padding,border and margin
    $('#content').outerHeight(true);

您可以将 content(ele) scrollheight 设置为内容的高度。

ele.scrollHeight

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM