make html text input field grow as I type?

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

    A couple of things come to mind:

    Use an onkeydown handler in your text field, measure the text*, and increase the text box size accordingly.

    Attach a :focus css class to your text box with a larger width. Then your box will be larger when focused. That's not exactly what you're asking for, but similar.

    * It's not straightforward to measure text in javascript. Check out this question for some ideas.

提交回复
热议问题