Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - Dynamically Adjust HTML Text Input Width to Content

I can't quite find a clear answer on this, and excuse me if there is one I've missed.

I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.

I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.

I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!

HTML:

<span><p>Hello, my name is </p></span>

<span><input type="text" id="input" class="form" placeholder="name"></span>

<span><p>. I am </p></span>

<span><input type="text" id="input" class="form" placeholder="age"></span>

    <span><p> years old.</p></span>

CSS:

.form {
    border: 0;
    text-align: center;
    outline: none;
}

span {
    display: inline-block;
}

p {
    font-family: arial;
}

Fiddle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One possible way:

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color:gray;
}
/* found this online --- it prevents the user from being able to make a (visible) newline */
[contenteditable=true] br{
  display:none;
}
<p>Hello, my name is <span id="name" contenteditable="true" placeholder="name"></span>. I am <span id="age" contenteditable="true" placeholder="age"></span> years old.</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...