make html text input field grow as I type?

前端 未结 12 1137
陌清茗
陌清茗 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:39

    How about programmatically modifying the size attribute on the input?

    Semantically (imo), this solution is better than the accepted solution because it still uses input fields for user input but it does introduce a little bit of jQuery. Soundcloud does something similar to this for their tagging.

    
    
    $('input').on('keydown', function(evt) {
        var $this = $(this),
            size = parseInt($this.attr('size'), 10),
            isValidKey = (evt.which >= 65 && evt.which <= 90) || // a-zA-Z
                         (evt.which >= 48 && evt.which <= 57) || // 0-9
                         evt.which === 32;
    
        if ( evt.which === 8 && size > 0 ) {
            // backspace
            $this.attr('size', size - 1);
        } else if ( isValidKey ) {
            // all other keystrokes
            $this.attr('size', size + 1);
        }
    });
    

    http://jsfiddle.net/Vu9ZT/

提交回复
热议问题