Make a
instead of
by pressing Enter on a contenteditable

前端 未结 2 608
梦毁少年i
梦毁少年i 2020-11-29 07:41

I\'ve written a bit of code in my keyboard event handler to insert a
in response to the press of the Enter key:

event.preventDefault(         


        
相关标签:
2条回答
  • 2020-11-29 08:16

    In order to solve your problem, always keep a br element as the last element of your contenteditable div. This will ensure predictable behavior when injecting a br element vs. the browser default of injecting div elements. You can check the lastChild on keyup and mouseup to make sure it's a br element. Assuming you have a document like:

    <div id="editable" contenteditable="true"></div>
    

    You can use the following JavaScript (w/ jQuery 1.4+) to keep a br element as the last element and inject a br element instead of div div:

    $(function(){
    
      $("#editable")
    
        // make sure br is always the lastChild of contenteditable
        .live("keyup mouseup", function(){
          if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
            this.appendChild(document.createChild("br"));
          }
        })
    
        // use br instead of div div
        .live("keypress", function(e){
          if (e.which == 13) {
            if (window.getSelection) {
              var selection = window.getSelection(),
                  range = selection.getRangeAt(0),
                  br = document.createElement("br");
              range.deleteContents();
              range.insertNode(br);
              range.setStartAfter(br);
              range.setEndAfter(br);
              range.collapse(false);
              selection.removeAllRanges();
              selection.addRange(range);
              return false;
            }
          }
        });
    
    });
    

    Tested on Apple OS X w/ Google Chrome 7, Mozilla Firefox 3.6, Apple Safari 5). Try using ierange to get this to work in Windows Internet Explorer.

    0 讨论(0)
  • 2020-11-29 08:22

    I would bind a function to the keyup event to delete and change to
    using regEx. So even if it creates strange markup, it will be fixed.

    Using jQuery:

    $('.myEditable').keyup(function(){
       var sanitazed = $(this).text().replace(/<div[^<]*?>/g, '').replace(/<\/div[^<]*?>/g, '<br>');
       $(this).text(sanitazed);
    });
    
    0 讨论(0)
提交回复
热议问题