简体   繁体   English

为新创建的DOM对象获取准确的维度

[英]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. 我正在动态创建DOM元素(更具体地说,使用jQuery创建包含一些带有css“width:auto”的文本的DIV,并在页面OnLoad事件中使用“font-face”字体)但是找到宽度在div不是预期的大小(具体而言,宽度是错误的)后, 立即创建它,并把它添加到DOM树。 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) 的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) 通过这个额外的超时延迟我的布局的完成,一切都很完美,所有元素大小完全符合预期(在Ubuntu Linux上的最新Chrome)

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? 然而,这个klugey计时器延迟冒犯了我的敏感性,显然是不安全的......有没有办法用特定的命令强制进行精确的尺寸计算? 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? 或者,是否有一个我可以注册的事件,只有在创建新的动态元素后,所有DOM元素的大小都正确才会触发? (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) (我正在想象IMG onload事件,它可以让你在加载后找出图像的正确尺寸)

tl;dr : Is there a guarantee as to when the width of a newly-created DOM object will be accurate? tl; dr :是否可以保证新创建的DOM对象的宽度何时准确?

Thanks for your help! 谢谢你的帮助!

How are you trying to get the width? 你是怎么试图获得宽度的? .css("width"), or .width(), .css(“width”)或.width(),

You should be using .width(), as .css("width') wont return anything except auto (if no width was specified in some style) 您应该使用.width(),因为.css(“width”)不会返回除auto之外的任何内容(如果在某些样式中未指定宽度)

$("#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. 您可以通过获取添加新div的元素的宽度来获得宽度。 Since the width of the new div is set to auto they should be the same. 由于新div的宽度设置为auto,因此它们应该相同。

This will however not work for the height. 然而,这对高度不起作用。

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

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