我在这个 jsfiddle http://jsfiddle.net/tovic/gLhCk/ 中找到了以下非常简单的方法来自动将文本区域调整为文本高度:
function expandTextarea(id) {
document.getElementById(id).addEventListener('keyup', function() {
this.style.overflow = 'hidden';
this.style.height = 0;
this.style.height = this.scrollHeight + 'px';
}, false);
}
expandTextarea('txtarea');
body {
padding:50px;
}
textarea {
margin:0px 0px;
padding:5px;
height:16px;
line-height:16px;
width:96%;
display:block;
margin:0px auto;
}
<textarea id="txtarea" spellcheck="false" placeholder="Statusku..."></textarea>
但是,我在我的项目中使用引导程序,这会带来问题。
- textarea 只有 4px 高而不是 16px。似乎 bootstrap 改变了边距、填充和高度的工作方式?
- 敲回车时,文字上下跳动,刺眼。
我试图删除浏览器的 HTML 检查器中的所有引导类,但问题仍然存在。有谁知道如何解决这个问题?
这是添加引导程序的 CSS 时的代码:
function expandTextarea(id) {
document.getElementById(id).addEventListener('keyup', function() {
this.style.overflow = 'hidden';
this.style.height = 0;
this.style.height = this.scrollHeight + 'px';
}, false);
}
expandTextarea('txtarea');
body {
padding:50px;
}
textarea {
margin:0px 0px;
padding:5px;
height:16px;
line-height:16px;
width:96%;
display:block;
margin:0px auto;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<textarea id="txtarea" spellcheck="false" placeholder="Statusku..."></textarea>
原文由 bersling 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢您的所有回答,它让我对我必须改变的东西有了宝贵的见解。最后,在 css 中增加一点 padding-bottom 就可以了。