Prevent dropping empty lines in IE by contenteditable = false

I have a div with contenteditable=true to enable inline editing (for RTE purposes).

Im aware that different browsers handle keypress input differently, FF inserts <br> and IE inserts <p>

The problem I am facing is entering text on different lines.

for example for text:

 line 1 line 2 line 3 line 4 

In FF, when you enter the above, then switch contenteditable=false , the formatting of the strings remains as expected.

However, when editing in IE with multiple lines of text, and then when setting contenteditable=false all empty lines are collapsed. eg:

 line 1 line 2 line 3 line 4 

If I then reset contenteditable=true , these folded lines will be restored.

I assume this has something to do with using <p> IE, any ideas on how I can prevent line folding when contenteditable=false ?

+4
source share
1 answer

You can try to work around this IE behavior by catching ENTER and adding BR instead of <P>&nbsp;</P> .

 pad.addEventListener('keydown',keyDown,false); function keyDown(e){ if(e.keyCode!=13) return; pad.innerHTML+='<br />\b'; e.stopPropagation(); e.preventDefault(); return false; } <div id="pad" contenteditable="true"></div> 

The trick is to add "\ b" (backspace) to the end of the line, otherwise IE will not make a new line before the user clicks on another key. However, these feedbacks cause problems when using innerHTML later. To remove backspaces, you simply replace them with "" on RegExp:

 padsInnerHTML=pad.innerHTML.replace(/LITERAL_BACKSPACE_CHARACTER/g,''); 

In a regular expression, you will need a literal backward character, /\b/ will not work. To see the reverse character, you can run your code in Opera using this keyDown() , write a few letters and press ENTER in the pad and copy-paste the character into your code.

Please note that this code should only work in IE, other browsers will be corrupted with new characters.


Why this works, I do not know. IE seems to add some non-print character after <BR /> , which needs to be removed to create an instant new line after pressing ENTER.

+1
source

Source: https://habr.com/ru/post/1412943/


All Articles