Frage

I have a div with contenteditable=true set in order to allow inline editing (for RTE purposes).

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

The issue I am experiencing is when entering text across various lines.

e.g for the text:

line 1
line 2

line 3


line 4

In FF, when entering the above then switching contenteditable=false, the line formatting remains as expected.

However, when editing in IE with multiple lines of text, then setting contenteditable=false, any blank lines are collapsed. e.g:

line 1
line 2   
line 3    
line 4

If I then reset contenteditable=true, these collapsed lines are restored.

I am guessing it has something to do with the use of <p> by IE, any ideas how I can prevent the lines from being collapsed when contenteditable=false?

War es hilfreich?

Lösung

You could try to walk 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 won't make newline before user hits another key. However, these backspaces are causing troubles when using innerHTML later. To remove backspaces, you just replace them with "" with RegExp:

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

In the regexp you'll need a literal backspace character, /\b/ won't work. To actually see the backspace character, you can run your code in Opera with this keyDown(), write some letters and hit ENTER in pad and copy-paste the character to your code.

Notice, that this code should run in IE only, other browsers will mess up with newlines.


Why is this working, I don't know. It seems, that IE adds some none-printing character after <BR />, which has to be removed to create an instant newline after pressing ENTER.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top