jQuery实现textarea高度根据内容自适应

时间:2021-01-04 14:24:52
 1         //jQuery实现textarea高度根据内容自适应
 2         $.fn.extend({
 3             txtaAutoHeight: function () {
 4                 return this.each(function () {
 5                     var $this = $(this);
 6                     if (!$this.attr('initAttrH')) {
 7                         $this.attr('initAttrH', $this.outerHeight());
 8                     }
 9                     setAutoHeight(this).on('input', function () {
10                         setAutoHeight(this);
11                     });
12                 });
13                 function setAutoHeight(elem) {
14                     var $obj = $(elem);
15                     return $obj.css({ height: $obj.attr('initAttrH'), 'overflow-y': 'hidden' }).height(elem.scrollHeight);
16                 }
17             }
18         });
19 
20         //调用
21         $(function () {
22             $("#txtaMain").txtaAutoHeight();
23         });