问题描述
我很想知道如何创建一个可自动调整高度的文本输入,以便适合文本的高度?例如,如果我开始输入一个段落,它会从几行扩展到适合该段落。
以下是我目前收到的内容:
#commenttext {width:413px; min-height:22px;最大高度:100%;显示:内联; font-size:11px;颜色:#777777;单词包装:分词; font-family:Open Sans,Tahoma; top:7px;位置:相对; left:7px; padding-left:7px;} < form action = method =POST> < input type =textid =commenttext>< / form>
但这只是一个普通的文本区域。
当我输入更多行时,如何让文本区域变得更高?我需要使用Javascript吗?
这是一个纯CSS解决方案:使用 div contenteditable 设为true。
< div contenteditable =true
style =width:200px; min-height:20px; border:1px solid #ccc;>< / div>
请参阅为例。
编辑:
如果您希望能够提交这段文字,你需要一点点的javascript把它放到 input 字段中。添加到您的表单:
< form onsubmit =document.getElementById('hidden_data')。value = document.getElementById ( 'showing_data')的innerHTML;>
< input id =hidden_dataname =datatype =hidden/>
< div id =showing_datacontenteditable =true
style =width:200px; min-height:20px; border:1px solid #ccc;>< / div>
< / form>
这会将 div 到一个隐藏的 input 字段中,这样它就会通过 POST 与其他任何东西一起提交给服务器。
有关示例,请参阅此(更新)。
I was wonder how I can create a text input that has an auto-adjustable height so that it gets taller to fit your text? For example, if I start typing a paragraph, it expands from a few lines to fit the paragraph.
Here's what I've currently got:
#commenttext { width: 413px; min-height: 22px; max-height: 100%; display: inline; font-size: 11px; color: #777777; word-wrap: break-word; font-family: "Open Sans", "Tahoma"; top: 7px; position: relative; left: 7px; padding-left: 7px; }
<form action="" method="POST"> <input type="text" id="commenttext"> </form>
But that's just a normal text area.
How can I make that text area get taller as I type more lines? Do I need Javascript?
Here's a CSS-only solution: Use a div with contenteditable set to true.
<div contenteditable="true" style="width:200px;min-height:20px;border:1px solid #ccc;"></div>
See this JSFiddle for an example.
EDIT:If you want to be able to submit this text, you'll need a little bit of javascript to put it into an input field. Add this to your form:
<form onsubmit="document.getElementById('hidden_data').value=document.getElementById('showing_data').innerHTML;"> <input id="hidden_data" name="data" type="hidden"/> <div id="showing_data" contenteditable="true" style="width:200px;min-height:20px;border:1px solid #ccc;"></div> </form>
This will put the contents of the div into a hidden input field so it will be submitted to the server through POST with anything else.
See this (updated) JSFiddle for an example.
这篇关于输入字段在输入时会变得更高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!