根据内容自动调整文本区域大小

在我的一个页面上,我有一个文本区html标签供用户写入一个字母。我希望文本区域下面的内容向下移动,换句话说,我希望文本区域垂直调整,每行添加一行到文本区域并使下面的内容简单地相对于文本区域的底部定位。

我希望javascript / jquery有一种方法来检测单词的换行时间,或者添加新行并基于它来调整文本区域容器的大小。

我的目标是使文本区域下方的内容与文本底部保持相同的距离,无论用户写多少。

文本区域在文本溢出时创建滚动条。

由于我对网上找到的几个解决方案不太满意,所以这是我的看法。

尊重最小高度,最大高度。 通过向高度添加缓冲区(当前为20,可以替换为行高),避免跳转并闪烁滚动条。 但是,当达到最大高度时仍会显示滚动条。 避免通过逐步减小textarea高度而不是将其设置为0来重置容器滚动位置。因此也会立即删除所有已删除的行。 适用于IE和Chrome,无需浏览器嗅探。

http://jsfiddle.net/Nd6B3/4/

 #ta { width:250px; min-height:116px; max-height:300px; resize:none; } $("#ta").keyup(function (e) { autoheight(this); }); function autoheight(a) { if (!$(a).prop('scrollTop')) { do { var b = $(a).prop('scrollHeight'); var h = $(a).height(); $(a).height(h - 5); } while (b && (b != $(a).prop('scrollHeight'))); }; $(a).height($(a).prop('scrollHeight') + 20); } autoheight($("#ta")); 

http://www.jacklmoore.com/autosize/

首先下载插件:

第1步:将“jquery.autoresize.min.js”放在你保存jquery插件的地方。

第2步:在HTML中链接文件 – > 确保此链接在您的jquery链接之后,在您自己之前javascript / jquery代码链接。

第3步:在你的javascript代码文件中添加$('#containerToBeResized').autosize();

 $('textarea').keyup(function (e) { var rows = $(this).val().split("\n"); $(this).prop('rows', rows.length); }); 

这个工作样本。

从这个答案中看到这个小提琴 。 这会根据行数增加textarea的高度。

我认为这就是你所要求的。

复制下面答案中的代码:

HTML

 

Code explanation: Textarea Auto Resize

JS

 /*global document:false, $:false */ var txt = $('#comments'), hiddenDiv = $(document.createElement('div')), content = null; txt.addClass('txtstuff'); hiddenDiv.addClass('hiddendiv common'); $('body').append(hiddenDiv); txt.on('keyup', function () { content = $(this).val(); content = content.replace(/\n/g, '
'); hiddenDiv.html(content + '
'); $(this).css('height', hiddenDiv.height()); });

CSS

 body { margin: 20px; } p { margin-bottom: 14px; } textarea { color: #444; padding: 5px; } .txtstuff { resize: none; /* remove this if you want the user to be able to resize it in modern browsers */ overflow: hidden; } .hiddendiv { display: none; white-space: pre-wrap; word-wrap: break-word; overflow-wrap: break-word; /* future version of deprecated 'word-wrap' */ } /* the styles for 'commmon' are applied to both the textarea and the hidden clone */ /* these must be the same for both */ .common { width: 500px; min-height: 50px; font-family: Arial, sans-serif; font-size: 13px; overflow: hidden; } .lbr { line-height: 3px; }