make html text input field grow as I type?

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

    I just wrote this for you, I hope you like it :) No guarantees that it's cross-browser, but I think it is :)

    (function(){
        var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');
    
        input.style.width = min+'px';
        input.onkeypress = input.onkeydown = input.onkeyup = function(){
            var input = this;
            setTimeout(function(){
                var tmp = document.createElement('div');
                tmp.style.padding = '0';
                if(getComputedStyle)
                    tmp.style.cssText = getComputedStyle(input, null).cssText;
                if(input.currentStyle)
                    tmp.style.cssText = input.currentStyle.cssText;
                tmp.style.width = '';
                tmp.style.position = 'absolute';
                tmp.innerHTML = input.value.replace(/&/g, "&")
                                           .replace(//g, ">")
                                           .replace(/"/g, """)
                                           .replace(/'/g, "'")
                                           .replace(/ /g, ' ');
                input.parentNode.appendChild(tmp);
                var width = tmp.clientWidth+pad_right+1;
                tmp.parentNode.removeChild(tmp);
                if(min <= width && width <= max)
                    input.style.width = width+'px';
            }, 1);
        }
    })();
    

    JSFiddle

提交回复
热议问题