我经常读到在读取元素样式后更改样式是一种不好的做法,因为它会触发不必要的重排。考虑来自 here 的这段代码:
错误代码:
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
好的代码:
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)
我很好奇为什么elementA.offsetHeight
会引起布局?在这里,我们只是读取已经应用的更改,而不是真正应用更改(例如 elementA.className = "a-style"
)。
最佳答案
Here we are simply reading already applied changes...
不是真的。分配给 className
意味着浏览器必须回流,但这并不意味着它在您完成分配后已经回流。它可能会等到(在现代浏览器中,将等到)它的下一次绘制,直到当前 JavaScript 代码完成(至少)之后才会发生。
但是当您读取像 clientHeight
这样的计算属性时,浏览器必须暂停 JavaScript 代码并重排页面,以便返回准确的数字。所以你的“好”代码是这样做的:
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
关于javascript - 为什么读取 DOM 测量会触发布局/回流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361968/