Insert newline on enter key in contenteditable div

后端 未结 3 1742
独厮守ぢ
独厮守ぢ 2021-01-18 23:53

I am trying to insert a newline character instead of whatever the browser wants to insert when I press enter in a contenteditable div.

My current code looks somethin

相关标签:
3条回答
  • 2021-01-19 00:16

    this works in IE 11 and chrome for me

    if(getSelection().modify) {     /* chrome */
      var selection = window.getSelection(),
        range = selection.getRangeAt(0),
        br = document.createTextNode('\n');
      range.deleteContents();
      range.insertNode(br);
      range.setStartAfter(br);
      range.setEndAfter(br);
      range.collapse(false);
      selection.removeAllRanges();
      selection.addRange(range);       /* end chrome */
    } else {
      document.createTextNode('\n');    /* internet explorer */
      var range = getSelection().getRangeAt(0);
      range.surroundContents(newline);
      range.selectNode(newline.nextSibling);   /* end Internet Explorer 11 */
    }
    

    sorry for how unorganized it is. I used getSelection().modify to determine if it was ie or not because IE doesn't have modify for some reason.

    0 讨论(0)
  • 2021-01-19 00:26

    Try this:

    document.execCommand('insertHTML', false, '<br><br>');
    

    Even undo\redo work :)

    0 讨论(0)
  • 2021-01-19 00:41

    something like this?

    if(e.which==13){
        e.preventDefault();
        $('#divID').html($('#divID').text()+"<br />");
    }
    
    0 讨论(0)
提交回复
热议问题