在添加到 DOM 之前获取元素的高度 [英] Getting the height of an element before added to the DOM

查看:36
本文介绍了在添加到 DOM 之前获取元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在将元素附加到 DOM 之前获取元素的高度?我知道 clientHeight 不能像我尝试的那样工作,它总是返回 0.是否还有其他方法可以返回高度,或者元素是否必须是 DOM 的一部分才能计算高度?

Is there any way to get an element's height prior to appending it to the DOM? I know that clientHeight doesn't work as I've tried and it always returns 0. Are there other methods that may return the height or does the element have to be a part of the DOM in order for the height to be calculated?

这是我要做的示例:

function test(a) {
    var a=document.createElement(a)
    a.style.top=(window.innerHeight/2-a.clientHeight/2)+'px' //fixed position in CSS
    document.body.appendChild(a)
    }

*注意:这只是我正在处理的功能的简化版本,以便在没有所有不必要的混乱的情况下投射我想要实现的目标.

*Note: This is only a simplified version of the function I'm working on in order to project what I'm trying to achieve without all of the unneeded mess.

推荐答案

元素没有高度,在任何真正意义上,直到它们被添加到 DOM,作为它们的样式在此之前无法评估.

Elements don't have a height, in any real sense, until they've been added to the DOM, as their styles cannot be evaluated until then.

您可以使用 visibility: hidden 轻松解决这个问题,这样可以将元素添加到 DOM(并确定其高度)而不会导致可见的闪烁.(jsFiddle)

You can get around this easily enough using visibility: hidden so that the element can be added to the DOM (and its height determined) without causing visible flickering. (jsFiddle)

function test(a) {
    var a=document.createElement(a);
    a.style.visibility = "hidden";
    document.body.appendChild(a);
    a.style.top=(window.innerHeight/2-a.clientHeight/2)+'px';
    a.style.visibility = "";
}

(这是在假设您使用 top 因为元素是绝对定位或固定的.如果不是,您需要临时设置它.)隐藏元素仍然占用 DOM 中的空间(因此必须计算它们的大小),但实际上无法被用户看到.

(This is working on the assumption that you're using top because the element is absolutely positioned or fixed. If it weren't, you'd need to make it so temporarily.) Hidden elements still take up space in the DOM (so their sizes must be calculated), but cannot actually be seen by the user.

这篇关于在添加到 DOM 之前获取元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆