得到的元件的高度添加到DOM之前 [英] Getting the height of an element before added to the DOM

查看:150
本文介绍了得到的元件的高度添加到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?

这就是我要去为我的一个样本:

This is a sample of what I'm going for:

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 = "";
}

(这是工作在您使用上面的假设,因为该元素绝对定位或固定的。如果不是这样,你需要做它所以暂时。)隐藏元素仍然占用空间在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天全站免登陆