Html 有没有办法让 textarea 在不使用 PHP 或 JavaScript 的情况下拉伸以适应其内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2803880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?
提问by significance
I am filling a textarea with content for the user to edit.
我正在用内容填充文本区域供用户编辑。
Is it possible to make it stretch to fit content with CSS (like overflow:show
for a div)?
是否可以使用 CSS 使其拉伸以适应内容(例如overflow:show
div)?
采纳答案by Rik Heywood
Not really. This is normally done using javascript.
并不真地。这通常是使用 javascript 完成的。
there is a good discussion of ways of doing this here...
这里有一个关于这样做的方法的很好的讨论......
回答by Martin Prestone
one line only
只有一行
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
回答by Chris Dutrow
Here is a function that works with jQuery (for height only, not width):
这是一个适用于 jQuery 的函数(仅适用于高度,不适用于宽度):
function setHeight(jq_in){
jq_in.each(function(index, elem){
// This line will work with pure Javascript (taken from NicB's answer):
elem.style.height = elem.scrollHeight+'px';
});
}
setHeight($('<put selector here>'));
Note:The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.
注意:op 要求提供一个不使用 Javascript 的解决方案,但这应该对许多遇到此问题的人有所帮助。
回答by NicB
This is a very simple solution, but it works for me:
这是一个非常简单的解决方案,但对我有用:
<!--TEXT-AREA-->
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>
<!--JAVASCRIPT-->
<script type="text/javascript">
function setHeight(fieldId){
document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
}
setHeight('textBox1');
</script>