javascript - 为什么设置 textContent 会导致布局抖动?

标签 javascript html performance dom

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>

image

但是将 innerText 替换为 textContent 并观察它的抖动:

image

有人可以解释这种行为吗?我该怎么做才能避免布局抖动并仍然以基于标准的方式更改元素的文本?

最佳答案

问题:

你是对的!就像你观察到的那样。设置 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.

修复

一种非颠簸的方法是获取元素的文本节点并修改它们,而不是使用 textContentinnerText(这是非标准的)。

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

当然,如果实际文本发生变化,则必须进行绘制以更新您所看到的内容。

profile

关于javascript - 为什么设置 textContent 会导致布局抖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199958/

相关文章:

html - 在元素的一半设置背景

sql - PostgreSQL:一次运行多个选择

javascript - gulp 4.0 : run tasks in series

javascript - 如何在 jQuery 中查找多个 div 值中的 div?

html - 如何根据内容设置元素的高度

html - CSS 显示内联属性对我不起作用

c# - check exists before add to list 和 linq 中的 distinct 之间的性能

c# - 为什么字典比列表快这么多?

javascript - 如何解析包含计算的字符串并执行它

javascript - Angular JS - 如何将选中的输入添加到数组中以及如何在取消选中后删除?