简体   繁体   中英

Getting Accurate Dimensions for a newly-created DOM object

I'm creating DOM elements dynamically (more specifically, using jQuery to create a DIV containing some text with css "width:auto", and using a "font-face" font, in the page OnLoad event) but find that the width of the div is not the expected size (specifically, the width is wrong) immediately after I create it and add it to the DOM tree. I need to know the width/height of the element because I will be doing some dynamic layout on it.

As a workaround, I use the following code after creating the elements:

SetTimeout(complete_layout,100)

By delaying the completion of my layout with this extra timeout, everything works perfectly, with all element sizes exactly as expected (In the latest Chrome on Ubuntu Linux)

However, this klugey timer delay offends my sensibilities and is clearly unsafe... Is there any way to force accurate dimension calculations with a specific command? Or, is there an event I can register that will fire only once all the DOM elements have been correctly sized, after new dynamic elements are created? (I am picturing something like the IMG onload event, which allows you to figure out the proper dimensions of an image once it has been loaded)

tl;dr : Is there a guarantee as to when the width of a newly-created DOM object will be accurate?

Thanks for your help!

How are you trying to get the width? .css("width"), or .width(),

You should be using .width(), as .css("width') wont return anything except auto (if no width was specified in some style)

$("#foo").width();

It should give width even after immediate appending.

You could get the width by getting the width of the element you add the new div to. Since the width of the new div is set to auto they should be the same.

This will however not work for the height.

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