This blog post建议 textContent
优于 innerText
以避免布局抖动。但它专注于检索元素的文本;对于 setting 元素文本,情况恰恰相反——至少在以下示例中是这样。
此示例使用 innerText
并且不会产生布局抖动:
<style>
#test {
background-color: blue;
float: right;
width: 100px;
height: 100%;
}
</style>
Test test test
<div id="test"></div>
<script>
setInterval(function() {
document.querySelector('#test').innerText = 'innerText';
}, 100);
</script>
但是将 innerText
替换为 textContent
并观察它的抖动:
有人可以解释这种行为吗?我该怎么做才能避免布局抖动并仍然以基于标准的方式更改元素的文本?
最佳答案
问题:
你是对的!就像你观察到的那样。设置 textContent
确实会导致抖动。
这是 DOM specification 的内容不得不说:
textContent of type DOMString, introduced in DOM Level 3
This attribute returns the text content of this node and its descendants. When it is defined to be null, setting it has no effect. On setting, any possible children this node may have are removed and, if it the new string is not empty or null, replaced by a single Text node containing the string this attribute is set to.
修复
一种非颠簸的方法是获取元素的文本节点并修改它们,而不是使用 textContent
或 innerText
(这是非标准的)。
var test = document.getElementById("test");
var a = document.createTextNode("");
test.appendChild(a);
setInterval(function(){
a.nodeValue = "Test test test";
},100);
Here is a working fiddle
当然,如果实际文本发生变化,则必须进行绘制以更新您所看到的内容。
关于javascript - 为什么设置 textContent 会导致布局抖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199958/