为新创建的DOM对象获取准确的维度 [英] Getting Accurate Dimensions for a newly-created DOM object

查看:122
本文介绍了为新创建的DOM对象获取准确的维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态地创建DOM元素(更具体地说,使用jQuery创建一个包含一些文本的DIV,包含csswidth:auto,并在OnLoad页面中使用font-face字体),但是发现在创建它之后,div的宽度不是预期的大小(具体来说,宽度是错误的)立即,并将其添加到DOM树中。我需要知道元素的宽度/高度,因为我将会做一些动态布局。



作为解决方法,我创建元素后使用以下代码:


SetTimeout(complete_layout,100)


通过延迟完成我的布局与这个额外的超时,一切工作完美,所有的元素大小完全按照预期(在最新的Chrome在Ubuntu Linux上)



然而,这个klugey定时器延迟冒犯我的感觉,显然不安全...有什么办法强制使用特定的命令的精确尺寸计算?或者,是否有一个事件我可以注册,只有一旦所有的DOM元素的大小正确,新的动态元素创建后, (我正在绘制像IMG onload事件,它允许您在加载图像后确定图像的正确尺寸)



tl; dr



感谢您的帮助!

解决方案

你想如何获取宽度?
.css(width)或.width(),



您应该使用.width()作为.css(width)不要返回除auto之外的任何东西(如果在某些样式中没有指定宽度)

  $(#foo)。 ; 

即使在即时附加后也应该给出宽度。


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.

这篇关于为新创建的DOM对象获取准确的维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆