Development Tip

contentEditable DIV에서 줄 바꿈 처리

yourdevel 2021. 1. 8. 22:29
반응형

contentEditable DIV에서 줄 바꿈 처리


contenteditableSAFARI / CHROME에서 줄 바꿈에 문제가 있습니다. contentEditable <div>에서 "return"을 누르면 <br>Firefox와 같은 파일 을 만드는 대신 다음을 새로 만듭니다 <div>.

<div>Something</div>
<div>Something</div>

(contentEditable DIV에서) 다음과 같습니다.

Something
Something

그러나 살균 후 (제거 <div>) 다음을 얻습니다.

SomethingSomething

Firefox에서는 다음 contenteditable과 같습니다.

Something
<br>
Something

그리고 살균 후에도 동일하게 보입니다.

Something
Something

여러 브라우저에서 "정규화"할 수있는 솔루션이 있습니까?

이 코드 는 <div> </ div> 대신 Make a <br>에서 Contenteditable에서 Enter 키를 눌러 찾았습니다.

$(function(){

  $("#editable")

  // make sure br is always the lastChild of contenteditable
  .live("keyup mouseup", function(){
    if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
      this.appendChild(document.createChild("br"));
     }
  })

  // use br instead of div div
  .live("keypress", function(e){
    if (e.which == 13) {
      if (window.getSelection) {
        var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br");
        range.deleteContents();
        range.insertNode(br);
        range.setStartAfter(br);
        range.setEndAfter(br);
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
        return false;
      }
    }
  });
});

이것은 작동하지만 (SAFARI 및 CHROME에서) 새 줄을 얻으려면 "return"키를 두 번 눌러야합니다.

어떤 생각?

Edit: With the code I found ( at the bottom of this question) is working fine except the function that "makes sure a <br> element is always the lastChild... Any idea on how to fix this?

Edit 2: I'm getting this error on the console: Uncaught TypeError: Object #<HTMLDocument> has no method 'createChild'

Edit 3: Ok, I changed the document.createChild("br"); to document.createElement("br"); and I think I got it working in FF/Safari/Chrome... All return <br> for new lines...

The problem is now that when I'm inside an Ordered or Unordered List, I need to get a new line without <br>...

Edit 4: If anyone interested in the solution of the last edit: Avoid createElement function if it's inside a <LI> element (contentEditable)


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 &nbsp; 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;
  }

   }
});

Listening to keystrokes seems like a lot of work. Would something as simple as this be feasible:

var html = $('.content').html().replace(/<div>/gi,'<br>').replace(/<\/div>/gi,'');

JSFiddle demo here.

Also, it looks like sanitize.js allows a custom configuration. Have you tried adding div as an allowed element?

Allowing HTML/CSS is dangerous, so ensure you are being extra cautious.

EDIT: Removed server side comments. Sanitising occurs at time of usage- if the client wants to bypass this locally it can be done so at their own risk. Thanks Vincent McNabb for pointing this out.


You can simply use following command document.execCommand('insertHTML',false,'<br>');

This command will prevent default behavior and add a tag you wish. That's all, 1 line of code

And even easier approach.

CSS ONLY.

To you contenteditable element apply display:inline-block rule and this will add brs only


Webkits won’t render a single br if it’s the last (non-empty) child of a container. For Safari, the native keystroke to insert a line break is Ctrl + Return. If you look closely, you notice that Safari actually inserts two brs while only rendering one; however, it will insert a single br if there is some trailing text, or will get rid of double brs once you enter some (if there were doubles).

Apparently, it seems a solution for Webkits is to insert double brs as they themselves do, and let them handle the rest.


You might want to check out the css white-space property. Setting the style to white-space: pre-wrap allows you to get rid of all that javascript, because it changes the behavior of whitespace to display instead of collapse.

And see this answer: HTML - Newline char in DIV content editable?


see this Fiddle

Or this post

How to parse editable DIV's text with browser compatibility


You can use:

document.execCommand("defaultParagraphSeparator", false, "br");

The complete reference is here

ReferenceURL : https://stackoverflow.com/questions/6023307/dealing-with-line-breaks-on-contenteditable-div

반응형