需求来源
在文本框输入过多内容时,会涌现滚动条,不雅观观也不舒适;又或者当文本框添补很多内容时,在删除部分内容,高度不会变革,看着好不雅观观不雅观。这时候,就须要做一个会自适应高度的文本框,根据内容来变革文本框高度。
html源码给每个textarea文本框加一个autoHeight属性,并设置其属性为true,以便于初始js时获取须要自适应高度的标签
<h3>自适应高度的textarea文本框</h3><textarea autoHeight="true"></textarea>
js源码
编写js代码,获取autoHeight属性为true的textarea标签,然后根据keyup事宜,每次书写完毕,获取文本框内容高度来设置文本框的高度,如下:

$(function(){ $.fn.autoHeight = function(){ function autoHeight(elem){ elem.style.height = 'auto'; elem.scrollTop = 0; //防抖动 elem.style.height = elem.scrollHeight + 'px'; } this.each(function(){ autoHeight(this); $(this).on('keyup', function(){ autoHeight(this); }); }); } $('textarea[autoHeight]').autoHeight();})
搬你想搬,盖你所需,码字不易,且行且珍惜!