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

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

问题描述

我需要在我的网络应用程序中准确测量文本的尺寸,我通过创建一个元素(具有相关的 CSS 类)、设置其 innerHTML 然后使用 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天全站免登陆