如何判断动态创建的元素何时呈现 [英] How to tell when a dynamically created element has rendered

查看:68
本文介绍了如何判断动态创建的元素何时呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要准确地测量我的网络应用程序中的文本尺寸,我通过创建一个元素(具有相关的CSS类)来实现,设置它的 innerHTML 然后添加它使用 appendChild 到容器。



在这样做之后,在元素渲染之前有一个等待,可以读取 offsetWidth ,以了解文本的宽度。



目前,我正在使用 setTimeout(processText,100)等待渲染完成。



有没有回调我可以听,或一个更可靠的方式来告诉我何时创建了一个元素?

解决方案

目前没有DOM事件表示元素已经完全呈现(例如,附加的CSS应用和绘制)。这可以使一些DOM操作代码返回错误或随机的结果(例如获取元素的高度)。



使用setTimeout给浏览器一些开销用于渲染是最简单的办法。使用

  setTimeout(function(){},0)

可能是最实际的准确性,因为它将您的代码放置在活动的浏览器事件队列的末尾,没有任何更多的延迟 - 换句话说,您的代码正好在渲染操作(以及当时发生的所有其他操作)。


I need to accurately measure the dimensions of text within my web app, which I am achieving by creating an element (with relevant CSS classes), setting its innerHTML then adding it to the container using appendChild.

After doing this, there is a wait before the element has been rendered and its offsetWidth can be read to find out how wide the text is.

Currently, I'm using setTimeout(processText, 100) to wait until the render is complete.

Is there any callback I can listen to, or a more reliable way of telling when an element I have created has been rendered?

解决方案

There is currently no DOM event indicating that an element has been fully rendered (eg. attached CSS applied and drawn). This can make some DOM manipulation code return wrong or random results (like getting the height of an element).

Using setTimeout to give the browser some overhead for rendering is the simplest way. Using

setTimeout(function(){}, 0)

is perhaps the most practically accurate, as it puts your code at the end of the active browser event queue without any more delay - in other words your code is queued right after the render operation (and all other operations happening at the time).

这篇关于如何判断动态创建的元素何时呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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