我正在填写textarea内容供用户编辑.
是否有可能使其伸展以适应CSS的内容(如overflow:show
div)?
Mar*_*one 124
只有一行
<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim 23
或者,您可以使用一个contenteditable
元素,这将适合内部的文本。
<div contenteditable>Try typing and returning.</div>
Run Code Online (Sandbox Code Playgroud)
请注意,如果不使用一些 JavaScript,则无法以表单形式发送该值。还contenteditable
可能生成 HTML 内容并允许样式化,因此可能需要在表单提交时将其过滤掉。
Mar*_*n93 13
与问题并非 100% 相关,因为这仅适用于使用Angular Material Design时的Angular。
有一个与 Angular 相关的 npm 包@angular/cdk
(如果使用 Angular Material Design)。此包中包含一个属性,可以与textarea
名为cdkTextareaAutosize 的属性关联。这会自动将 设置textarea
为 1 行并textarea
相应地拉伸 来适合内容。如果您正在使用这个库,类似的东西应该可以工作。
<textarea
maxLength="200"
cdkTextareaAutosize
type="text">
</textarea>
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单的解决方案,但对我有用:
<!--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>
Run Code Online (Sandbox Code Playgroud)
这是一个与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>'));
Run Code Online (Sandbox Code Playgroud)
注意: 操作系统要求提供不使用Javascript的解决方案,但这应该对遇到此问题的人有所帮助.
这里的答案很好,但缺少一段代码,我必须添加这些代码以避免第一次键入时不受欢迎的收缩:
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';
});
Run Code Online (Sandbox Code Playgroud)
动态 textarea 控件的另一个简单解决方案。
<!--JAVASCRIPT-->
<script type="text/javascript">
$('textarea').on('input', function () {
this.style.height = "";
this.style.height = this.scrollHeight + "px";
});
</script>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
69987 次 |
最近记录: |