简体   繁体   English

HTML / CSS / JS:在将元素附加到DOM树之前是否可以找到元素的大小?

[英]HTML / CSS/ JS: Is it possible to find the element's size before appending it to the DOM tree?

I'm creating some HTML elements dynamically via JavaScript. 我正在通过JavaScript动态创建一些HTML元素。 Something line this: 有点像这样:

        var author  = document.createElement("div");
        author.innerHTML = _feed[i].author;
        author.className = "author";

The browser returns offsetHeight = 0 if the element is not added to the document yet. 如果元素尚未添加到文档中,则浏览器返回offsetHeight = 0

I want to know the element's height before appending them to the document because if the element's resulting height is too big I need to take some actions (make it smaller), and only after that add it to the document. 我想在将元素附加到文档之前知道元素的高度,因为如果元素的结果高度太大,我需要采取一些操作(使其变小),然后才将其添加到文档中。

My suggestion is to add it to the page with a left margin of -10000 or something, so that it's not visible. 我的建议是将它添加到页面左边距为-10000或其他东西,这样它就不可见了。 Then you can get the dimensions, do what you need, and then change the left margin so that it's where you want it. 然后你可以获得尺寸,做你需要的,然后改变左边距,使它在你想要的位置。 This is assuming you would use absolute positioning. 这是假设您将使用绝对定位。

But so far as I know, the browser will not report that information on elements not in the DOM. 但据我所知,浏览器不会报告不在DOM中的元素的信息。

Dan the problem you are going to have is that unless you add it to the DOM then you can never accurately know what the height will be. Dan你将遇到的问题是,除非你把它添加到DOM,否则你永远无法准确知道它的高度。 The reason for this is that as the element is not in the DOM, it cannot be affected by styles set in CSS or the browsers default styles. 原因是由于元素不在DOM中,因此不能受CSS中设置的样式或浏览器默认样式的影响。 Even if the element itself has no specific styles applied to it then its parent element may do, or even its grandparent element (did I just make grandparent element up?). 即使元素本身没有特定的样式,也可以使用其父元素,甚至可以使用其祖父母元素(我是否只是将祖父母元素组成?)。

The only accurate way of getting the height is to place the element exactly where it will sit in the DOM and then detect the height. 获得高度的唯一准确方法是将元素准确放置在DOM中的位置,然后检测高度。 I don't think visibility:hidden; 我不认为visibility:hidden; will work as its presence will still be felt by elements around it (pushing margins around and positioning of other elements). 会起作用,因为它周围的元素仍然会感觉到它的存在(在其他元素周围增加边距和定位)。

How about position:absolute; left: -5000px; position:absolute; left: -5000px;如何position:absolute; left: -5000px; position:absolute; left: -5000px; ? That may work. 这可能有用。

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

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