簡體   English   中英

使用javascript編輯HTML:插入\\ n而不是 <br> 作為新線

[英]Edit HTML with javascript: Insert \n instead of <br> as a new line

我正在使用以下代碼在內容可編輯的HTML文檔中插入新行:

execCommand("insertHTML", false, '\n');

這在Chrome和Safari中對我有效,但在其他瀏覽器中會產生<br>或新段落。 因為我正在編輯<pre>標記,所以我不希望瀏覽器將\\ n更改為<br>。 我怎樣才能做到這一點?

我已經嘗試過使用range.insertNode()之類的功能或在FireFox中操縱insertBrOnReturn,但是它始終是相同的。 在沒有瀏覽器更改輸入的情況下,沒有辦法在文檔中插入\\ n嗎?

我認為沒有跨瀏覽器的工作方式可以添加\\n ...我對contenteditable並不熟悉,但是由於它正在更改innerHTML,因此您可以執行以下操作

var currentContent = myContent; // "currentContent holds" the current content
execCommand("insertHTML", false, '\n'); // inserts the line break
if (newContent !== currentContent + '\n') { // "newContent" holds the content afterwards
  console.log('use String.prototype.replace to replace created tag with "\n"');
}

我假設您以后要保存編輯后的內容,那么在獲取標記內容時如何用\\n替換所有<br>呢? 像這樣:

document.getElementById("editable").innerHTML.replace(/<br>/g, "\n");

編輯:您也可以只使用innerText而不是innerHTML。 這樣做時,所有換行符都顯示為<br>標記(至少我在Chrome中得到了該結果)。 這個解決方案雖然不好,但是至少總是一樣的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM