简体   繁体   中英

Script insert line breaks in div contentEditable

I have a webpage div with contentEditable=true . After the user modifies the content of the div, the system uses document.getElementById(id).innerHTML to get the content and send it to server. This is all working:

<div id='editBox'; contentEditable='true'></div>
<script>
document.getElementById('editBox').onkeydown=function(e){
    clearTimeout ( backupTimeoutID );
    backupTimeoutID = setTimeout(function(){sendDivContentToServer()},3000);
}
<script>

the reason I'm using the a div with contentEditable=true instead of text area is that I need to allow displaying and formatting of background-colored text in the div. If I'm unaware of any better way, please, let me know.

My problem is with the inconsistence with which line breaks are displayed. If the user presses return inside the div, it creates another div for the line break. So, when the function gets the innerHtml, it looks like this

first line of text<div>second line of text</div>

Sometimes, when pasting text from other sources in the edit box (from internet, word, etc), line breaks appear as <p> .

I want all line breaks to look like this:

first line of text<br>second line of text

I have tried changing the behavior of the <div> whenever the user presses return; I know the code is working, for if I try to insert a word instead of return it works. But, when I set the code to substitute return for <br> it acts erradically. This is the code I'm using for this:

<script>
document.getElementById('editBox').onkeydown=function(e){
    clearTimeout ( backupTimeoutID );
    backupTimeoutID = setTimeout(function(){sendDivContentToServer()},3000);
}
} else if ( pressedKeyCode==13 ) {
    e.preventDefault();
    document.execCommand("InsertHTML",false,"a"); // this works
    document.execCommand("InsertHTML",false,"<br>"); // I don't see the effects I want with this
}
<script>

Converting the multiple line breaks – <div> , <p> and <br> – seem to be a hard task. Using <br> for line breaks seems less error prone.

I'm developing for a web viewer in FileMaker for use in Mac OSX. So, so far, I care more about Safari than any other browser.

Thanks, in advance, for the help.

Reining in contentEditable is not an easy task. Unfortunately it's not really standardized and every browser has its quirks.

I would suggest you have a look at the many well written HTML rich text editors that are around.

For example, CKEditor only creates sensible, valid HTML, it allows you to configure what happens, when the user presses return , it can remove or replace any unwanted HTML and you can disable any features that the user shouldn't use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM