make html text input field grow as I type?

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

    Here's a method that worked for me. When you type into the field, it puts that text into the hidden span, then gets its new width and applies it to the input field. It grows and shrinks with your input, with a safeguard against the input virtually disappearing when you erase all input. Tested in Chrome. (EDIT: works in Safari, Firefox and Edge at the time of this edit)

    function travel_keyup(e)
    {
        if (e.target.value.length == 0) return;
        var oSpan=document.querySelector('#menu-enter-travel span');
        oSpan.textContent=e.target.value;
        match_span(e.target, oSpan);
    }
    function travel_keydown(e)
    {
        if (e.key.length == 1)
        {
            if (e.target.maxLength == e.target.value.length) return;
            var oSpan=document.querySelector('#menu-enter-travel span');
            oSpan.textContent=e.target.value + '' + e.key;
            match_span(e.target, oSpan);
        }
    }
    function match_span(oInput, oSpan)
    {
        oInput.style.width=oSpan.getBoundingClientRect().width + 'px';
    }
    
    window.addEventListener('load', function()
    {
        var oInput=document.querySelector('#menu-enter-travel input');
        oInput.addEventListener('keyup', travel_keyup);
        oInput.addEventListener('keydown', travel_keydown);
    
        match_span(oInput, document.querySelector('#menu-enter-travel span'));
    });
    #menu-enter-travel input
    {
    	width: 8px;
    }
    #menu-enter-travel span
    {
    	visibility: hidden;
        position: absolute;
        top: 0px;
        left: 0px;
    }

提交回复
热议问题