javascript - 我可以使用 javascript 强制浏览器 "flush"任何未决的布局更改吗?

标签 javascript dom layout browser

我有一个使用 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/

相关文章:

css - 将布局更改为固定,居中,同时调整页脚以固定在底部

javascript - 类似 Angular 的 Javascript 服务依赖注入(inject)

javascript - Express 中的动态 URL 和静态路由

javascript - 为什么跨源工作人员被阻止,为什么解决方法可以?

c - webkit_dom_element_get_elements_by_tag_name 无法正常工作

javascript - 在这种情况下如何改善大表格的显示?

ios - View 中有多个圆角

javascript - 页面和 iframe 加载前白屏闪烁

php - 如何解析 <a name 和 <image src= inside <li tag using php?

ASP.NET:向导控件的自定义布局