简体   繁体   中英

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. 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.

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. 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.

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. 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. 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. I don't think 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; ? That may work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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