我正在用用户编辑的内容填充文本区域。
是否可以使其拉伸以适合CSS的内容(例如overflow:show
div)?
Answers:
仅一行
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
this.scrollHeight + "px"
改为this.scrollHeight + 3 + "px"
可使文本区域足够大,以使其不显示滚动条。
这是一个适用于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>'));
注意: op要求使用不使用Javascript的解决方案,但是这对遇到此问题的许多人都将有所帮助。
这是一个非常简单的解决方案,但对我有用:
<!--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>
<style> textarea { resize: none; overflow: auto; } </style> <!--TEXT-AREA--> <textarea onkeyup="setHeight.call(this);">Hello World</textarea> <!--JAVASCRIPT--> <script type="text/javascript"> function setHeight(){ this.style.height = '1px'; this.style.height = this.scrollHeight + 'px'; } </script>
由于以下原因,基本上您必须首先将高度设置为1px:stackoverflow.com/questions/10722058/…–
动态文本区域控件的另一个简单解决方案。
<!--JAVASCRIPT-->
<script type="text/javascript">
$('textarea').on('input', function () {
this.style.height = "";
this.style.height = this.scrollHeight + "px";
});
</script>