正如其他人解释的那样,input
字段不能包含多行文本,您应该使用它textarea
来模仿输入字段,并使用jQuery使它自动垂直调整大小(具有固定宽度)。
:
//This span is used to measure the size of the textarea
//it should have the same font and text with the textarea and should be hidden
var span = $('<span>').css('display','inline-block')
.css('word-break','break-all')
.appendTo('body').css('visibility','hidden');
function initSpan(textarea){
span.text(textarea.text())
.width(textarea.width())
.css('font',textarea.css('font'));
}
$('textarea').on({
input: function(){
var text = $(this).val();
span.text(text);
$(this).height(text ? span.height() : '1.1em');
},
focus: function(){
initSpan($(this));
},
keypress: function(e){
//cancel the Enter keystroke, otherwise a new line will be created
//This ensures the correct behavior when user types Enter
//into an input field
if(e.which == 13) e.preventDefault();
}
});
:
textarea {
width:200px;
resize:none;
overflow:hidden;
font-size:18px;
height:1.1em;
padding:2px;
}
这个新的更新的演示已修复了一些错误,并且还支持Enter键,最大高度限制,宽度不需要首先固定设置(相反,我们可以设置其最小宽度)。功能更加强大。