如何获得元素的渲染高度?
假设您有一个<div>
包含一些内容的元素。里面的这个内容将拉伸<div>
. 当您没有明确设置高度时,如何获得“渲染”高度。显然,我尝试过:
var h = document.getElementById('someDiv').style.height;
这样做有诀窍吗?如果有帮助,我正在使用 jQuery。
尝试以下之一:
var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
clientHeight
包括高度和垂直填充。
offsetHeight
包括高度、垂直填充和垂直边框。
scrollHeight
包括包含文档的高度(在滚动的情况下会大于高度)、垂直填充和垂直边框。
它应该只是
$('#someDiv').height();
用 jQuery。这将检索包装集中第一项的高度作为数字。
尝试使用
.style.height
仅在您首先设置属性时才有效。不是很有用!
NON JQUERY ,因为在这些答案的顶部使用了一堆链接......elem.style.height
内部高度:
https ://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight
document.getElementById(id_attribute_value).clientHeight;
外部高度:
https ://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetHeight
document.getElementById(id_attribute_value).offsetHeight;
或者我最喜欢的参考资料之一:http: //youmightnotneedjquery.com/
我用它来获取元素的高度(返回浮点数):
document.getElementById('someDiv').getBoundingClientRect().height
当您使用虚拟 DOM时,它也可以工作。我在 Vue 中这样使用它:
this.$refs['some-ref'].getBoundingClientRect().height
对于 Vue 组件:
this.$refs['some-ref'].$el.getBoundingClientRect().height
您可以.outerHeight()
用于此目的。
它将为您提供元素的完整渲染高度。此外,您不需要设置任何css-height
元素。为了预防起见,您可以将其高度保持为自动,以便可以根据内容的高度进行渲染。
//if you need height of div excluding margin/padding/border
$('#someDiv').height();
//if you need height of div with padding but without border + margin
$('#someDiv').innerHeight();
// if you need height of div including padding and border
$('#someDiv').outerHeight();
//and at last for including border + margin + padding, can use
$('#someDiv').outerHeight(true);
要清楚地了解这些功能,您可以访问 jQuery 的站点或此处的详细帖子。
它将清除//之间的区别.height()
innerHeight()
outerHeight()
style = window.getComputedStyle(your_element);
然后简单地说:style.height
绝对用
$('#someDiv').height() // to read it
或者
$('#someDiv').height(newHeight) // to set it
我将其作为附加答案发布,因为我刚刚学到了一些重要的东西。
刚才我差点掉进了使用offsetHeight的陷阱。这就是发生的事情:
这只是其中的一部分:
Math.max(
Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
Math.max(document.body["offset" + name], document.documentElement["offset" + name])
)
是的,它同时查看滚动和偏移。如果失败,考虑到浏览器和 css 兼容性问题,它看起来会更进一步。换句话说,我不关心的东西——或者想要的东西。
但我不必。谢谢 jQuery!
故事的寓意:如果 jQuery 有某种方法,它可能是有充分理由的,可能与兼容性有关。
如果您最近还没有阅读jQuery 方法列表,我建议您看一下。
我认为在 2020 年做到这一点的最好方法是使用 vanilla js 和getBoundingClientRect().height;
这是一个例子
let div = document.querySelector('div');
let divHeight = div.getBoundingClientRect().height;
console.log(`Div Height: ${divHeight}`);
<div>
How high am I?
</div>
除了获得height
这种方式之外,我们还可以访问有关div
.
let div = document.querySelector('div');
let divInfo = div.getBoundingClientRect();
console.log(divInfo);
<div>What else am I? </div>
我编写了一个甚至不需要 JQuery 的简单代码,并且可能会帮助一些人。加载后获取“ID1”的总高度并在“ID2”上使用
function anyName(){
var varname=document.getElementById('ID1').offsetHeight;
document.getElementById('ID2').style.height=varname+'px';
}
然后只需设置身体加载它
<body onload='anyName()'>
document.querySelector('.project_list_div').offsetHeight;
嗯,我们可以得到元素几何......
var geometry;
geometry={};
var element=document.getElementById(#ibims);
var rect = element.getBoundingClientRect();
this.geometry.top=rect.top;
this.geometry.right=rect.right;
this.geometry.bottom=rect.bottom;
this.geometry.left=rect.left;
this.geometry.height=this.geometry.bottom-this.geometry.top;
this.geometry.width=this.geometry.right-this.geometry.left;
console.log(this.geometry);
这个普通的 JS 怎么样?
这就是答案吗?
“如果你需要计算但不显示它,请将元素设置为visibility:hidden
and position:absolute
,将其添加到 DOM 树中,获取 offsetHeight,然后将其删除。(这就是我上次检查时原型库在行后面所做的)。”
我在许多元素上都有同样的问题。该站点上没有要使用的 jQuery 或 Prototype,但如果它有效,我都赞成借用该技术。作为一些失败的例子,接下来是什么,我有以下代码:
// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
var DoOffset = true;
if (!elementPassed) { return 0; }
if (!elementPassed.style) { return 0; }
var thisHeight = 0;
var heightBase = parseInt(elementPassed.style.height);
var heightOffset = parseInt(elementPassed.offsetHeight);
var heightScroll = parseInt(elementPassed.scrollHeight);
var heightClient = parseInt(elementPassed.clientHeight);
var heightNode = 0;
var heightRects = 0;
//
if (DoBase) {
if (heightBase > thisHeight) { thisHeight = heightBase; }
}
if (DoOffset) {
if (heightOffset > thisHeight) { thisHeight = heightOffset; }
}
if (DoScroll) {
if (heightScroll > thisHeight) { thisHeight = heightScroll; }
}
//
if (thisHeight == 0) { thisHeight = heightClient; }
//
if (thisHeight == 0) {
// Dom Add:
// all else failed so use the protype approach...
var elBodyTempContainer = document.getElementById('BodyTempContainer');
elBodyTempContainer.appendChild(elementPassed);
heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
elBodyTempContainer.removeChild(elementPassed);
if (heightNode > thisHeight) { thisHeight = heightNode; }
//
// Bounding Rect:
// Or this approach...
var clientRects = elementPassed.getClientRects();
heightRects = clientRects.height;
if (heightRects > thisHeight) { thisHeight = heightRects; }
}
//
// Default height not appropriate here
// if (thisHeight == 0) { thisHeight = elementHeightDefault; }
if (thisHeight > 3000) {
// ERROR
thisHeight = 3000;
}
return thisHeight;
}
它基本上尝试任何事情,只是为了得到零结果。ClientHeight 没有影响。对于问题元素,我通常在 Base 中得到 NaN,在 Offset 和 Scroll 高度中得到零。然后我尝试了 Add DOM 解决方案和 clientRects 看看它是否在这里工作。
2011 年 6 月 29 日,我确实更新了代码以尝试同时添加到 DOM 和 clientHeight,结果比我预期的要好。
1)clientHeight 也是 0。
2) Dom 实际上给了我一个很棒的高度。
3) ClientRects 返回的结果几乎与 DOM 技术相同。
因为添加的元素本质上是流动的,所以当它们被添加到原本为空的 DOM Temp 元素时,它们会根据该容器的宽度进行渲染。这很奇怪,因为它比最终结束的时间短 30px。
我添加了一些快照来说明如何以不同方式计算高度。
身高差距很明显。我当然可以添加绝对定位和隐藏,但我相信这不会有任何效果。我继续坚信这行不通!
(我进一步离题)高度出来(渲染)低于真实渲染的高度。这可以通过设置 DOM Temp 元素的宽度以匹配现有父元素来解决,并且理论上可以相当准确地完成。我也不知道删除它们并将它们添加回现有位置会产生什么结果。当他们通过innerHTML 技术到达时,我将使用这种不同的方法进行研究。
* 但是 *这些都不是必需的。事实上,它像宣传的那样工作并返回了正确的高度!!!
当我能够让菜单再次可见时,令人惊讶的是,DOM 已经根据页面顶部的流畅布局返回了正确的高度(279 像素)。上面的代码还使用了返回 280px 的 getClientRects。
这在以下快照中进行了说明(从 Chrome 中获取)。
现在我不知道为什么该原型技巧有效,但似乎有效。或者,getClientRects 也可以。
我怀疑这些特定元素的所有这些问题的原因是使用了 innerHTML 而不是 appendChild,但目前这纯粹是猜测。
offsetHeight
, 通常。
如果您需要计算某些东西但不显示它,请将元素设置为visibility:hidden
and position:absolute
,将其添加到 DOM 树中,获取offsetHeight
,然后将其删除。(这就是我上次检查时原型库在幕后所做的事情)。
有时 offsetHeight 会返回零,因为您创建的元素尚未在 Dom 中呈现。我为这种情况编写了这个函数:
function getHeight(element)
{
var e = element.cloneNode(true);
e.style.visibility = "hidden";
document.body.appendChild(e);
var height = e.offsetHeight + 0;
document.body.removeChild(e);
e.style.visibility = "visible";
return height;
}
如果您已经在使用 jQuery,那么最好的选择是.outerHeight()
or .height()
,如前所述。
如果没有 jQuery,您可以检查使用中的 box-sizing 并添加各种填充 + 边框 + clientHeight,或者您可以使用getComputedStyle:
var h = getComputedStyle(document.getElementById('someDiv')).height;
h
现在将是一个类似“53.825px”的字符串。
而且我找不到参考,但我想我听说getComputedStyle()
可能很昂贵,所以它可能不是你想在每个window.onscroll
事件上调用的东西(但是,jQuery 也不是height()
)。
使用MooTools:
$('someDiv').getSize().y
如果我正确理解了您的问题,那么也许这样的事情会有所帮助:
function testDistance(node1, node2) {
/* get top position of node 1 */
let n1Pos = node1.offsetTop;
/* get height of node 1 */
let n1Height = node1.clientHeight;
/* get top position of node 2 */
let n2Pos = node2.offsetTop;
/* get height of node 2 */
let n2Height = node2.clientHeight;
/* add height of both nodes */
let heightTogether = n1Height + n2Height;
/* calculate distance from top of node 1 to bottom of node 2 */
let actualDistance = (n2Pos + n2Height) - n1Pos;
/* if the distance between top of node 1 and bottom of node 2
is bigger than their heights combined, than there is something between them */
if (actualDistance > heightTogether) {
/* do something here if they are not together */
console.log('they are not together');
} else {
/* do something here if they are together */
console.log('together');
}
}
您是否专门在css中设置了高度?如果你没有,你需要使用offsetHeight;
而不是height
var h = document.getElementById('someDiv').style.offsetHeight;