我对分配给 textContent
的字符串的呈现行为感到困惑当它包含 \r
时对比\n
.
MDN说:
The textContent property of the Node interface represents the text content of the node and its descendants.
那为什么 textContent
包含 \r
的文本谁申请了pre
不使用线制动器渲染,而 \n
做?
var textWithCR = "line1\rline2\r";
document.getElementById('crWithTextContent').textContent = textWithCR;
document.getElementById('crWithInnerHTML').innerHTML = textWithCR;
document.getElementById('crWithInnerText').innerText = textWithCR;
var textWithLF = "line3\nline4\n";
document.getElementById('lfWithTextContent').textContent = textWithLF;
document.getElementById('lfWithInnerHTML').innerHTML = textWithLF;
document.getElementById('lfWithInnerText').innerText = textWithLF;
.formatted {
white-space: pre-wrap;
}
<div id="crWithTextContent" class="formatted"></div><br/>
<div id="crWithInnerHTML" class="formatted"></div><br/>
<div id="crWithInnerText" class="formatted"></div><br/>
<div id="lfWithTextContent" class="formatted"></div><br/>
<div id="lfWithInnerHTML" class="formatted"></div><br/>
<div id="lfWithInnerText" class="formatted"></div>
我还查看了 spec ,它说:
This attribute returns the text content of this node and its descendants. [...]
On getting, no serialization is performed, the returned string does not contain any markup.
No whitespace normalization is performed and the returned string does not contain the white spaces in element content [...]
好吧,如果“返回的字符串不包含元素内容中的空格”,那么为什么在下面的代码中看起来是\n
当我们得到 textContent
时存在(通过在控制台上打印),而 \r
不是吗?
var textWithCR = "line1\rline2\r";
document.getElementById('crWithTextContent').textContent = textWithCR;
var textWithLF = "line3\nline4\n";
document.getElementById('lfWithTextContent').textContent = textWithLF;
console.log(document.getElementById('crWithTextContent').textContent);
console.log(document.getElementById('lfWithTextContent').textContent);
.formatted {
white-space: pre-wrap;
}
<div id="crWithTextContent" class="formatted"></div><br/>
<div id="lfWithTextContent" class="formatted"></div>
这是什么原因textContent
当它包含 \r
时的行为?
最佳答案
您的 \r
(U+000D CR) 在索引 5 处:
const elem = document.getElementById('test');
elem.textContent = "line1\rline2\r";
console.log( elem.textContent );
console.log( elem.textContent.charCodeAt( 5 ) ); // 13
console.log( "\r".charCodeAt( 0 ) ); // same char
<div id="test"></div>
您面临的问题是 CSS 没有将 U+000D CR 定义为 segment-break ,HTML 也没有。
HTML 当它normalizes newlines会将所有 \r\n
序列转换为 \n
,然后将所有剩余的 \r
转换为 \n
,因此有效地摆脱所有孤独的 \r
字符。但是,Node.textContent
不会调用此normalize-newlines 算法,因此它们不会转换为 \n
也不会被解释为 < em>分段符。
为此,您需要通过其他方法设置元素的内容,该方法将调用此算法,但这样做会丢失原始数据。
const elem = document.getElementById('test');
elem.innerHTML = "line1\rline2\r";
console.log( elem.textContent );
console.log( elem.textContent.charCodeAt( 5 ) ); // converted to \n (U+000A => 10)
#test { white-space: pre-wrap }
<div id="test"></div>
关于javascript - 为什么在分配给 textContent 时回车不呈现为换行符,尽管使用 pre 进行了格式化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965834/