Force IE contentEditable element to create line breaks on Enter key, without breaking Undo

前端 未结 7 1849
时光取名叫无心
时光取名叫无心 2020-12-05 06:59

On Internet Explorer, a contentEditable DIV creates a new paragraph (

) each time you press Enter whereas Firefox creates a
<
7条回答
  •  时光说笑
    2020-12-05 07:29

    IE binds the text node with a

    tag on Enter key press. To achieve a line break Shift+Enter. Firefox adds a
    tag on Enter key press. To make the behavior common across both the browsers, you can do the following:

    Assume the following markup:

    Javascript [assume the below code is in a function closure so that you don't bloat the page with globals]:

     (function () {
         //Initialize _shiftKeyPressed to false
         var _shiftKeyPressed = false;
         $('#editableDiv').live('keydown', function (e) {
             if (e.keyCode == 16) {
                 // SHIFT key is pressed
                 _shiftKeyPressed = true;
             }
         }).live('keyup', function (e) {
             if (e.keyCode == 16) {
                 // SHIFT key is release
                 _shiftKeyPressed = false;
             }
         }).live('keypress', function (e) {
             if (e.keyCode == 13 && !_shiftKeyPressed && !jQuery.browser.msie) {
                 // Insert a PARAGRAPH in Firefox instead of a BR
                 // Ignores SHIFT + ENTER
                 document.execCommand("insertParagraph", false, true);
             }
         })
     })();
    

    Note: this script is prior to jQuery < 1.9 for the use of the deprecated $.browser

提交回复
热议问题