根据键入字段的字符数动态扩展输入类型“文本”的高度

类似于下面的JSFiddle(我collections并且不知道原始问题出现在哪里):

http://jsfiddle.net/mJMpw/6/

 input { width: 200px; min-width: 200px; max-width: 300px; transition: width 0.25s; } 

有没有办法将文本字段的宽度固定为,例如200px,如果用户添加的文本比200px能够包含的文本多,文本字段的高度会增长? 我想要添加更多行,如果用户需要更多空间来键入…所以我需要高度而不是宽度来动态resize。

谢谢!

正如其他人所解释的那样, input字段不能有多行文本,你应该使用textarea模仿输入字段,而jQuery使它自动调整垂直大小(固定宽度)。

JS

 //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 = $('').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(); } }); 

CSS

 textarea { width:200px; resize:none; overflow:hidden; font-size:18px; height:1.1em; padding:2px; } 

演示。

更新演示:

这个新的更新演示修复了一些错误,它还支持Enter键,max-height限制,首先不需要固定设置宽度(而是我们可以设置其最小宽度)。 它的function更全面。

更新了演示

修订版[2]:

由于scrollHeight总是等于height ,我们必须在scrollHeight之前将height设置为‘1’ ,然后当我们删除字符时 autofit:

 $('textarea').on('keydown', function(e){ if(e.which == 13) {e.preventDefault();} }).on('input', function(){ $(this).height(1); var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom')); $(this).height(totalHeight); }); 

小提琴:

http://jsfiddle.net/mJMpw/551/

更新:

正如朋友所说, 没有换行符。 我建议使用是:

 $('textarea').on({input: function(){ var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom')); $(this).css({'height':totalHeight}); } }); 

小提琴:

http://jsfiddle.net/mJMpw/548/

原始答案:

这非常难看,但你可以这样做:

 $('input[type="text"]').on('keyup',function(){ var text = $(this).val(); var getWidth = $('' + text + '').insertAfter(this); $(this).css({'width':getWidth.outerWidth()}).next('.getWidth').remove(); }); 

您必须为.getWidth指定相同的字体/填充属性,并输入:

 input, .getWidth { font-family:arial; font-size:12px; font-weight:normal; letter-spacing:normal; padding:3px; } 

小提琴:

http://jsfiddle.net/9SMRf/