make html text input field grow as I type?

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

    If you are just interested in growing, you can update the width to scrollWidth, whenever the content of the input element changes.

    document.querySelectorAll('input[type="text"]').forEach(function(node) {
      node.onchange = node.oninput = function() {
        node.style.width = node.scrollWidth+'px';
      };
    });
    

    But this will not shrink the element.

提交回复
热议问题