Dealing with line Breaks on contentEditable DIV

后端 未结 7 1771
粉色の甜心
粉色の甜心 2020-11-27 12:41

I have a problem with contenteditable line breaks on SAFARI/CHROME. When I press \"return\" on a contentEditable

, instead of creating a
7条回答
  •  北海茫月
    2020-11-27 13:03

    This technique appears to avoid the Chrome bug that does show BRs the first time (with the code you mentionned you need to push two times the Enter key).

    It's not a perfect hack but it works: it adds a whitespace after your BR so it show properly. However, you will see that adding only a whitespace " " will NOT change anything, it works with other letters. The browser will not show it, probably because it is like a blank space inside an html page, it simply does not mean anything. To get rid of that bug I created a div with jQuery that includes a   tag, and I take the text() property to put it in the textnode otherwise it doesn't work.

    $editables = $('[contenteditable=true]');
    
    $editables.filter("p,span").on('keypress',function(e){
     if(e.keyCode==13){ //enter && shift
    
      e.preventDefault(); //Prevent default browser behavior
      if (window.getSelection) {
          var selection = window.getSelection(),
              range = selection.getRangeAt(0),
              br = document.createElement("br"),
              textNode = document.createTextNode("\u00a0"); //Passing " " directly will not end up being shown correctly
          range.deleteContents();//required or not?
          range.insertNode(br);
          range.collapse(false);
          range.insertNode(textNode);
          range.selectNodeContents(textNode);
    
          selection.removeAllRanges();
          selection.addRange(range);
          return false;
      }
    
       }
    });
    

提交回复
热议问题