avoid ie contentEditable element to create paragraphs on Enter key

后端 未结 5 1878
小蘑菇
小蘑菇 2020-12-06 06:49

On InternetExplorer, a contentEditable DIV creates a new paragraph (

) each time you press Enter whereas Firefox creates a
相关标签:
5条回答
  • 2020-12-06 07:05

    You can always learn to use SHIFT + ENTER for single line returns and ENTER for paragraph returns. IE behaves like MS Word in this respect.

    0 讨论(0)
  • 2020-12-06 07:12

    Changing the line-height of the <p> inside the editable <div> works:

    #editable_div p
    {
        line-height: 0px;
    }
    
    0 讨论(0)
  • 2020-12-06 07:28

    Yes it is possible to avoid the insertion of paragraphs by stopping the keydown event first (window.event.stopPropagation();) and then inserting the string by using insert HTML command.

    However, IE depends on this divs for setting styles etc. and you will get into trouble using <br>s.

    I suggest you using a project like TinyMCE or other editors and search for an editor which behaves the way you would like, since they have all kinds of workarounds for different browser issues. Perhaps you can find an editor which uses <br>s...

    0 讨论(0)
  • 2020-12-06 07:28

    Here's a solution (uses jQuery). After you click on the 'Change to BR' button, the <br> tag will be inserted instead of the <p></p> tag.

    Html:

    <div id='editable' contentEditable="true">
    This is a division that is content editable. You can position the cursor 
    within the text, move the cursor with the arrow keys, and use the keyboard 
    to enter or delete text at the cursor position.
    </div>
    <button type="button" onclick='InsertBR()'>Change to BR</button>
    <button type="button" onclick='ViewSource()'>View Div source</button>
    

    Javascript:

    function InsertBR()
    {
        $("#editable").keypress(function(e) {
            if (e.which == 13) 
            {
                e.preventDefault();
                document.selection.createRange().pasteHTML("<br/>")     
            }
        });
    }
    
    function ViewSource()
    {           
        var div = document.getElementById('editable');
        alert('div.innerHTML = ' + div.innerHTML);
    }
    

    These links helped. Working example here.

    0 讨论(0)
  • 2020-12-06 07:30

    If you can use it, FCKEditor has a setting for this

    0 讨论(0)
提交回复
热议问题