我能够根据行数来增加textarea的大小,但是我没有按Enter键,只是输入文本,然后它不起作用,textarea的大小也不起作用。请参阅以下小提琴。
$("textarea").on("keyup", function($event) {
this.rows = (this.value.split("\n").length||1);
var thisTextArea = $event.currentTarget;
if (thisTextArea.value.split("\n").length > 5) {
thisTextArea.rows = (thisTextArea.value.split("\n").length);
$(thisTextArea).css("overflow-y","hidden");
if (thisTextArea.rows > 15) {
$(thisTextArea).css("overflow-y","scroll");
}
}
else {
thisTextArea.rows = 6;
$(thisTextArea).css("overflow-y","hidden");
}
});
<textarea rows="5"></textarea>
Fiddle Link
最佳答案
$(document)
.one('focus.textarea', '.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.textarea', '.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0,
rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
html
<textarea rows="5"class='autoExpand'></textarea>
的CSS
textarea{
display:block;
box-sizing: padding-box;
overflow:hidden;
padding:10px;
width:250px;
font-size:14px;
margin:50px auto;
border-radius:8px;
border:6px solid #556677;
}
link here