我使用此代码在内容可编辑的 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"');
}
关于javascript - 使用 javascript 编辑 HTML : Insert\n instead of <br> as a new line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460672/