为新创建的 DOM 对象获取准确的尺寸

发布于 2024-10-11 05:00:38 字数 601 浏览 8 评论 0原文

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

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

设置超时(complete_layout,100)

通过用这个额外的超时来延迟布局的完成,一切都完美地工作,所有元素的大小都完全符合预期(在 Ubuntu Linux 上的最新 Chrome 中)

但是,这个 klugey 计时器延迟冒犯了我的敏感性,并且显然不安全...有什么方法可以使用特定命令强制进行精确的尺寸计算吗?或者,是否有一个我可以注册的事件,只有在创建新的动态元素后,所有 DOM 元素的大小都正确调整后才会触发? (我想象的是类似 IMG onload 事件的东西,它允许您在加载图像后计算出图像的正确尺寸)

tl;dr:是否可以保证新创建的 DOM 对象会准确吗?

感谢您的帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰沐子 2024-10-18 05:00:38

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

您应该使用 .width(),因为 .css("width') 不会返回除 auto 之外的任何内容(如果在某些样式中未指定宽度)

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

它应该给出宽度即使在立即附加之后。

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.

我的鱼塘能养鲲 2024-10-18 05:00:38

您可以通过获取添加新 div 的元素的宽度来获取宽度。由于新 div 的宽度设置为 auto,因此它们应该相同。

然而,这不适用于高度。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文