【发布时间】:2022-06-11 17:32:36
【问题描述】:
有没有办法让 HTML 正确处理 \\n 换行符?或者我必须用<br/> 替换它们?
<div class=\"text\">
abc
def
ghi
</div>
标签: html
有没有办法让 HTML 正确处理 \\n 换行符?或者我必须用<br/> 替换它们?
<div class=\"text\">
abc
def
ghi
</div>
标签: html
这是为了在 HTML 中显示新行和回车,然后你不需要明确地这样做。您可以在 CSS 中通过设置 white-space 属性前行值来实现。
<span style="white-space: pre-line">@Model.CommentText</span>
【讨论】:
white-space: pre-wrap。
您可以将 CSS white-space 属性用于 \n。您还可以像\t 一样保留选项卡。
对于换行符\n:
white-space: pre-line;
对于换行符\n 和制表符\t:
white-space: pre-wrap;
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
#just-line-break {
white-space: pre-line;
}
#line-break-and-tab {
white-space: pre-wrap;
}
<div id="just-line-break"></div>
<br/>
<div id="line-break-and-tab"></div>
【讨论】:
根据您的问题,可以通过多种方式完成。
例如,如果要在文本区域中插入新行,可以使用这些:
&#10; 换行和&#13; 回车,使用如下:
<textarea>Hello &#10;&#13;Stackoverflow</textarea>
您还可以使用 <pre>---</pre> 预格式化文本,如下所示:
<pre>
This is line 1
This is line 2
This is line 3
</pre>
或者你可以像这样使用<p>----</p> 段落标签:
<p>This is line 1</p>
<p>This is line 2</p>
<p>This is line 3</p>
【讨论】:
您可以使用<pre> 标签
<div class="text">
<pre>
abc
def
ghi
</pre>
abc
def
ghi
</div>
【讨论】:
使用white-space: pre-line 允许您直接在HTML 中输入带有换行符的文本,而无需使用\n
如果您使用innerText通过 JavaScript 在非 pre 元素上的元素属性,例如一个<div>,默认情况下,\n在DOM中的值将被替换为<br>
innerText:将\n 替换为<br>
innerHTML,textContent:需要使用样式white-space
这取决于您如何应用文本,但有多种选择
const node = document.createElement('div');
node.innerText = '\n Test \n One '
【讨论】:
br 行为取决于浏览器——因此不太可能将其描述为单个文档。我很少使用innerText,但经常使用white-space 样式
你可以使用<pre> 标签:
<div class="text">
<pre>
abc
def
ghi
</pre>
</div>
【讨论】:
简单而线性:
<p> my phrase is this..<br>
the other line is this<br>
the end is this other phrase..
</p>
【讨论】:
您可以使用以下任何 CSS,
white-space: pre-line;
或者
white-space: pre-wrap;
或者
white-space: break-spaces;
欲了解更多信息,请阅读:https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
【讨论】:
一个不涉及 CSS 样式或数字字符引用(如 &#13;&#10;)的简单且更自然的解决方案是使用 &NewLine; 字符实体引用:
The primary colors are:
- Red
- Green
- Blue
笔记:由于这被简单地定义为 LF(换行,或U+000A Unicode 代码点)字符,它是否适合需要整个 CR + LF(回车 + 换行)序列的场景是有争议的。但是,它在我在 Windows 10 中完成的 Chrome、Edge 和 WebView2 测试中工作,所以它应该可以安全使用。
【讨论】: