是否有“元素渲染"事件? [英] Is there 'element rendered' event?

查看:48
本文介绍了是否有“元素渲染"事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Web应用程序中准确测量文本的尺寸,这是通过创建一个元素(具有相关的CSS类),设置其 innerHTML ,然后使用 appendChild .

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.

完成此操作后,需要等待一段时间才能渲染元素,并且可以读取其 offsetWidth 来确定文本的宽度.

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.

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

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?

推荐答案

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

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).

使用setTimeout为浏览器提供一些渲染开销是最简单的方法.使用

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天全站免登陆