make html text input field grow as I type?

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

    Which approach you use, of course, depends on what your end goal is. If you want to submit the results with a form then using native form elements means you don't have to use scripting to submit. Also, if scripting is turned off then the fallback still works without the fancy grow-shrink effects. If you want to get the plain text out of a contenteditable element you can always also use scripting like node.textContent to strip out the html that the browsers insert in the user input.

    This version uses native form elements with slight refinements on some of the previous posts.

    It allows the content to shrink as well.

    Use this in combination with CSS for better control.