我填写的内容用户编辑文本区。
是否有可能使其延伸以适应 CSS 内容(如用于 div 的 overflow:show) ?
overflow:show
不完全是。这通常是用 javascript 完成的。
在这里有一个很好的讨论这样做的方式..。
使用 Prototype 自动调整文本区
这是一个非常简单的解决方案,但对我来说很有效:
<!--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>
下面是一个使用 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>'));
注: 这个操作要求一个不使用 Javascript 的解决方案,但是这对于遇到这个问题的很多人来说应该是有帮助的。
只有一句台词
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
动态纹理控制的另一个简单解决方案。
<!--JAVASCRIPT--> <script type="text/javascript"> $('textarea').on('input', function () { this.style.height = ""; this.style.height = this.scrollHeight + "px"; }); </script>
这里的答案不错,但缺少一段代码,我必须添加这段代码,以避免第一次输入时出现不受欢迎的缩写:
var $textareas = $('textarea'); $textareas.each(function() { // to avoid the shrinking this.style.minHeight = this.offsetHeight + 'px'; }); $textareas.on('input', function() { this.style.height = ''; this.style.height = this.scrollHeight + 'px'; });
或者,您可以使用 contenteditable元素,这将适合内部的文本。
contenteditable
<div contenteditable>Try typing and returning.</div>
请注意,如果不使用一些 javascript,就不可能在表单中发送这个值。此外,contenteditable可能会生成 HTML 内容,并允许样式,所以这可能需要在表单提交时过滤掉。
做出反应解决方案
我使用了显示的文本长度,并将这个数字除以30(我调整了这个数字,直到它在我的应用程序中显示正确)
{array.map((text) => ( <textarea rows={text.length / 30} value={text} ></textarea> )}
不是100% 相关的问题,因为这是为 角度时,使用 角度材料设计只。
有一个与角度相关的 npm 包称为 @angular/cdk(如果使用角度材料设计)。这个包中包含一个属性,它可以关联到称为 自动大小的 textarea。这会自动将 textarea设置为1行,并相应地拉伸 textarea以适应内容。如果您正在使用这个库,那么这样的方法应该可以工作。
@angular/cdk
textarea
<textarea maxLength="200" cdkTextareaAutosize type="text"> </textarea>
这里已经有很多答案,但是我认为文本区调整代码仍然可以做一些改进。
这个脚本片段将循环遍历页面上的所有文本区域,并确保它们在加载和更改时调整大小。
<script> document.querySelectorAll("textarea").forEach(element => { function autoResize(el) { el.style.height = el.scrollHeight + 'px'; } autoResize(element); element.addEventListener('input', () => autoResize(element)); }); </script>
只有香草 JS,不需要库。