How to make a content editable div behave like a text area?

后端 未结 2 1030
情歌与酒
情歌与酒 2021-02-06 07:48

I have built an editor that converts markdown to html. Right now I have to use jquery autosize plugin to resize the text area as it grows.

If I use a content-editable di

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-06 08:19

    Edit

    After the @Mr_Green comment above, you should have a look at Make a
    instead of

    by pressing Enter on a contenteditable

    The JS code to make it right is :

    $(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;
            }
          }
        });
    
    })
    

    ;


    You can intercept the Enter key press and replace it with a
    with Javascript :

    $(function(){
        
          $("#editable").keypress(function(e) {
            if (e.which == 13) {
                e.preventDefault();
                
                 if (document.selection) {
                    document.selection.createRange().pasteHTML("
    "); } else { $(this).append("
    "); } } }); });

提交回复
热议问题