Dynamically expand height of input type “text” based on number of characters typed into field

后端 未结 3 1247
遇见更好的自我
遇见更好的自我 2020-12-01 10:26

Similar to the below JSFiddle (which I bookmarked and do not know from where the original question emerged):

http://jsfiddle.net/mJMpw/6/



        
3条回答
  •  萌比男神i
    2020-12-01 10:54

    As others explained, input field can't have multiline text, you should use textarea to mimic an input field, and jQuery to make it auto resize vertically (with fixed width).

    JS:

    //This span is used to measure the size of the textarea
    //it should have the same font and text with the textarea and should be hidden
    var span = $('').css('display','inline-block')
                          .css('word-break','break-all')
                          .appendTo('body').css('visibility','hidden');
    function initSpan(textarea){
      span.text(textarea.text())
          .width(textarea.width())
          .css('font',textarea.css('font'));
    }
    $('textarea').on({
        input: function(){
           var text = $(this).val();      
           span.text(text);      
           $(this).height(text ? span.height() : '1.1em');
        },
        focus: function(){           
           initSpan($(this));
        },
        keypress: function(e){
           //cancel the Enter keystroke, otherwise a new line will be created
           //This ensures the correct behavior when user types Enter 
           //into an input field
           if(e.which == 13) e.preventDefault();
        }
    });
    

    CSS:

    textarea {
      width:200px;
      resize:none;
      overflow:hidden;
      font-size:18px;
      height:1.1em;
      padding:2px;
    }
    

    Demo.

    Updated Demo:

    This new updated demo has some bugs fixed and it also supports Enter key, max-height limit, the width does not need to be set fixedly at first (instead we can set its min-width). It's much more full-featured.

    Updated Demo

提交回复
热议问题