javascript - 使用 javascript 编辑 HTML : Insert\n instead of <br> as a new line

标签 javascript dom wysiwyg

我使用此代码在内容可编辑的 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/

相关文章:

android - 如何加载这些元素来填充 android 中的列表?

javascript - .getElementById 的内联 SVG 和 HTML DOM 范围

jquery - 如何更改tinymce中的默认字体大小?

xml - 开源 DocBook 编辑器

javascript - 我无法在数据列表中获取输入的值?

没有正则表达式的 JavaScript titleCase 函数

javascript - Nodemailer 无法在路由文件夹中工作

java - 如何将 HTMLDocument 分配到 JEditorPane 中以作为源代码进行修改?

javascript - 如何以全屏模式启动 TinyMCE 4?

javascript - 所有脚本和页面加载完成后如何获取所有html数据? ( puppeteer 师)