[英]Line break in HTML with '\n'
有沒有辦法讓 HTML 正確處理\n
換行符? 或者我必須用<br/>
替換它們?
<div class="text"> abc def ghi </div>
這是為了在 HTML 中顯示新行和回車,然后你不需要明確地這樣做。 您可以在 CSS 中通過設置 white-space 屬性前行值來實現。
<span style="white-space: pre-line">@Model.CommentText</span>
您可以將 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>
根據您的問題,可以通過多種方式完成。
例如,如果要在文本區域中插入新行,可以使用這些:
換行和
回車,這樣使用:
<textarea>Hello 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
如果您通過 JavaScript 在非 pre 元素(例如<div>
)上使用元素的innerText
屬性,則\n
值將默認替換為 DOM 中的<br>
innerText
: 用<br>
替換\n
innerHTML
, textContent
:需要使用樣式white-space
這取決於您如何應用文本,但有多種選擇
const node = document.createElement('div');
node.innerText = '\n Test \n One '
你可以使用<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
有沒有辦法讓 HTML 正確處理\\n
換行符? 或者我必須用<br/>
替換它們?
你可以使用 CSS 屬性
white-space: pre-line
一個簡單且更自然的解決方案,不涉及 CSS 樣式或數字字符引用,如
將使用

人物實體參考:
The primary colors are:
- Red
- Green
- Blue
注意:由於這被簡單地定義為 LF(換行,或U+000A
Unicode 代碼點)字符,因此它是否適合需要整個 CR + LF(回車 + 換行)序列的場景可能存在爭議。 但是,它在我在 Windows 10 中完成的 Chrome、Edge 和 WebView2 測試中工作,所以它應該可以安全使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.