问题描述
哪些DOM元素属性可以导致浏览器执行回流操作?
-
innerHTML
-
offsetParent
-
style
-
scrollTop
不能影响大小的属性或者背景颜色等元素的位置不应该触发回流,尽管不能保证每个浏览器都足够聪明实现。
在您的列表中:
innerHTML
更改对象的HTML,当然可以影响大小和位置,并将至少触发部分回流
offsetParent
对我而言是一个只读属性,不是直接设置的东西,因此阅读如果没有另外安排,它不应该导致回流。
style
是批量的网关的属性,包括 height
和 width
,这显然会导致至少部分回流。
scrollTop
n因为布局通常不会改变,只是一个元素的滚动位置(它是孩子),不会导致回流。布局应该保持不变,只需要重新绘制。
大概值得一提的是,导致回流的大多数属性不会立即导致回流,而是他们将来在短时间内安排回流。这样一来,如果一些javascript运行会改变一堆不同的属性,每个属性都需要回流,那么浏览器不会进行N回流,而是调度回流,等待当前执行的JavaScript线程完成,那么它只需要一次就可以进行任何回流。有一些属性,当读取时,导致所有待完成的回流现在要完成,因为如果没有立即完成回流,这些属性可能具有不准确的值。您可以在以前的帖子中阅读:
Which of these DOM element properties can cause browser to perform a reflow operation?
innerHTML
offsetParent
style
scrollTop
In a nutshell, any property that causes an element to change size or move will cause a reflow because that change of size or position can affect other elements. Browsers spend effort trying to be as efficient as possible to identify what might need to be reflowed, but each has a different way of doing that.
Properties that cannot affect the size or position of an element such as a background color should not trigger a reflow, though there is no guarantee that every browser is smart enough to implement this.
In your list:
innerHTML
changes the HTML of an object which certainly can affect size and position and will trigger at least a partial reflow.
offsetParent
appears to me to be a read-only property that isn't something you set directly so reading it shouldn't cause a reflow if one wasn't otherwise already scheduled.
style
is the gateway to lots of properties, including height
and width
which obviously would lead to at least a partial reflow.
scrollTop
need not cause a reflow because layout is generally not changed, just a scroll position of one element (and it's children). The layout should remain the same, just a repaint is required.
It's probably worth saying also that most properties that lead to a reflow, don't immediately cause that reflow, but rather they schedule the reflow for some short time in the future. That way, if some javascript runs that changes a bunch of different properties, each of which needs a reflow, the browser isn't doing N reflows, but rather, it schedules the reflow, waits for the current javascript thread of execution to finish and then it carries out whatever reflows are needed just once. There are some properties that when read, cause all reflows that are pending to be done now because those properties could have inaccurate values if the reflows aren't done right away. You can read about that in this earlier post: Forcing a DOM refresh in Internet explorer after javascript dom manipulation
这篇关于哪些DOM元素属性可以导致浏览器在修改时执行回流操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!