一般文本域的写法以下bootstrap
<textarea type="text" class="form-control pull-left" id="description" name="description"></textarea>
在页面的显示效果以下this
通常会有一个初始高度,当不对该文本域进行处理,文本域的高度不会发生变化,当文本域内的内容过多时,将会出现滚动条,效果以下spa
效果不美观。code
如今想让文本域的高度随内容的多少而发生改变,且不会产生滚动条。orm
能够使用如下代码blog
$('textarea').each(function () { this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;'); }).on('input', function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; });
显示效果以下ip
该文本域的高度会随着内容的增多而变大,也会随着内容的减小而减少。实时变化。input
有时候状况会比较复杂,例如我在作一个项目,前台使用的是bootstrap,使用model模态框弹出一个页面,在页面上有一个文本域,保持本来的代码保持不变,效果就发生了变化。io
我猜测这种效果的出现多是由于弹出框的高度和宽度问题。function
后来改了一下代码,首先给文本域一个默认高度
<textarea type="text" class="form-control pull-left" id="description" name="description" style="height: 50px"></textarea>
文本域获得焦点后,再实时监控文本域里的内容,而后让高度随之变化。
$("#description").focus(function () { $('textarea').each(function () { this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;'); }).on('input', function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); });