Can I use javascript to force the browser to “flush” any pending layout changes?

前端 未结 4 1463
庸人自扰
庸人自扰 2020-12-11 04:01

I have a library that build UI using Javascript, and because of the dynamic content involved I sometimes want to put content out to the browser, examine how the layout was c

4条回答
  •  感情败类
    2020-12-11 04:36

    My understanding is that reading any of the CSS properties will force a reflow. You should not need to setTimeout at all.

    Excerpt from 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.

    (This answer used to link to a site that 404s now. Here's a link to it in the wayback machine.)

提交回复
热议问题