简体   繁体   English

为什么读取 DOM 测量值会触发布局/回流?

[英]Why does reading DOM measurements trigger a layout/reflow?

I often read that changing a style after reading the element's style is a bad practice as it triggers an unnecessary reflow.我经常读到在阅读元素的样式后更改样式是一种不好的做法,因为它会触发不必要的回流。 Consider this code from here :考虑从这个代码在这里

Bad Code:错误代码:

elementA.className = "a-style";
var heightA = elementA.offsetHeight;  // layout is needed
elementB.className = "b-style";       // invalidates the layout
var heightB = elementB.offsetHeight;  // layout is needed again

Good code:好的代码:

elementA.className = "a-style";
elementB.className = "b-style";
var heightA = elementA.offsetHeight;   // layout is needed and calculated
var heightB = elementB.offsetHeight;   // layout is up-to-date (no work)

I am curious to know why elementA.offsetHeight will cause a layout?我很想知道为什么elementA.offsetHeight会导致布局? Here we are simply reading already applied changes, not really applying a change (like in case of elementA.className = "a-style" ).在这里,我们只是读取已经应用的更改,而不是真正应用更改(例如elementA.className = "a-style" )。

Here we are simply reading already applied changes...在这里,我们只是阅读已经应用的更改...

Not really.并不真地。 Assigning to className means the browser has to reflow, but it doesn't mean it already has reflowed when you're done assigning.分配给className意味着浏览器必须重排,但这并不意味着当您完成分配时它已经重排 It may wait (in modern browsers, will wait) until its next paint, which won't happen until after the current JavaScript code completes (at least).它可能会等待(在现代浏览器中,会等待)直到它的下一次绘制,直到当前的 JavaScript 代码完成(至少)之后才会发生。

But when you read a calculated property like clientHeight , the browser has to pause the JavaScript code and reflow the page so it can return an accurate number.但是当您读取像clientHeight这样的计算属性时,浏览器必须暂停 JavaScript 代码并重排页面,以便它可以返回准确的数字。 So your "good" code does this:所以你的“好”代码是这样的:

elementA.className = "a-style";        // marks the layout stale
elementB.className = "b-style";        // marks the layout stale (no change)
var heightA = elementA.offsetHeight;   // triggers reflow
var heightB = elementB.offsetHeight;   // no need for reflow, the layout isn't stale

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM