在用户新闻Ctrl+Enter时,我要插入一个新的行文。
Based on the following questions, I wrote the code below:
- Insert newline on enter key in contenteditable div
- How to insert a <CR> (Carriage Return) in a Javascript String?
- Dealing with line Breaks on contentEditable DIV
- Problem detecting Newlines in JavaScript Range Object
这里是我的超文本:
<span id="myInput" contenteditable="true" style="white-space: pre;"></span>
Here本:
let myInput = document.getElementById( myInput );
myInput.addEventListener( keypress , (event) => {
if (event.key == Enter && event.ctrlKey == true) {
event.preventDefault();
this.insertNewLine();
}
})
function insertNewLine(text) {
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
// Do not always works
var textNode = document.createTextNode("
");
// Always works
//var textNode = document.createTextNode("
u200b");
range.insertNode(textNode);
range.setStartAfter(textNode);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
当用户新闻Ctrl+Enter时,行为是:
- On Chrome, the new line is not always inserted
- On Firefox, the new line is inserted, but the caret does not jump to the next line
I noticed that the above code always works when an zero-width space (u200b
) is added after the
character.
I made a JSFidle: https://jsfiddle.net/Alphonsio/atr7e2uw/27/
Of course, I d prefer not to insert the second character. But I can t figure out why the new line is not inserted in the first case (
only). Can anyone help?