Insert newline on enter key in contenteditable div

后端 未结 3 1749
独厮守ぢ
独厮守ぢ 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.

提交回复
热议问题