我有一个使用 Javascript 构建 UI 的库,由于涉及动态内容,我有时想将内容输出到浏览器,检查如何更改布局以支持此功能,然后根据结果执行不同的逻辑.例如:检测某些文本是否溢出并用省略号将其 chop 。
通常我通过发布更改来实现这一点,然后使用 window.setTimeout(0) 等待布局更新并调用其余逻辑。这显然是次优的,因为不同的浏览器可能会实现一个太慢而无法防止闪烁的最小超时,或者会更快地使用大量 CPU。
理想情况下,我想更改 DOM,然后强制布局同步更新并立即内联运行“修复”逻辑。有什么想法吗?
最佳答案
我的理解是读取任何 CSS 属性都会强制重排。您根本不需要 setTimeout
。
摘自 Rendering: repaint, reflow/relayout, restyle :
But sometimes the script may prevent the browser from optimizing the reflows, and cause it to flush the queue and perform all batched changes. This happens when you request style information, such as
offsetTop, offsetLeft, offsetWidth, offsetHeight scrollTop/Left/Width/Height clientTop/Left/Width/Height getComputedStyle(), or currentStyle in IE
All of these above are essentially requesting style information about a node, and any time you do it, the browser has to give you the most up-to-date value. In order to do so, it needs to apply all scheduled changes, flush the queue, bite the bullet and do the reflow.
Here's a list of the API calls/properties that will trigger a reflow .
(这个答案曾经链接到现在 404s 的网站。Here's a link to it in the wayback machine。)
关于javascript - 我可以使用 javascript 强制浏览器 "flush"任何未决的布局更改吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6955912/