make html text input field grow as I type?

前端 未结 12 1202
陌清茗
陌清茗 2020-11-27 12:02

I can set initial text input size in css, like so:

width: 50px;

But I would like it to grow when I type until it reaches for example 200px.

12条回答
  •  盖世英雄少女心
    2020-11-27 12:35

    Here you can try something like this

    EDIT: REVISED EXAMPLE (added one new solution) http://jsfiddle.net/jszjz/10/

    Code explanation

    var jqThis = $('#adjinput'), //object of the input field in jQuery
        fontSize = parseInt( jqThis.css('font-size') ) / 2, //its font-size
        //its min Width (the box won't become smaller than this
        minWidth= parseInt( jqThis.css('min-width') ), 
        //its maxWidth (the box won't become bigger than this)
        maxWidth= parseInt( jqThis.css('max-width') );
    
    jqThis.bind('keydown', function(e){ //on key down
       var newVal = (this.value.length * fontSize); //compute the new width
    
       if( newVal  > minWidth && newVal <= maxWidth ) //check to see if it is within Min and Max
           this.style.width = newVal + 'px'; //update the value.
    });
    

    and the css is pretty straightforward too

    #adjinput{
        max-width:200px !important;
        width:40px;
        min-width:40px;
        font-size:11px;
    }
    

    EDIT: Another solution is to havethe user type what he wants and on blur (focus out), grab the string (in the same font size) place it in a div - count the div's width - and then with a nice animate with a cool easing effect update the input fields width. The only drawback is that the input field will remain "small" while the user types. Or you can add a timeout : ) you can check such a kind of solution on the fiddle above too!

提交回复
热议问题