Jquery实现textarea根据文本内容自适应高度

时间:2023-03-08 20:40:46
Jquery实现textarea根据文本内容自适应高度

本文给大家分享的是Jquery实现textarea根据文本内容自适应高度,这些在平时的项目中挺实用的,所以抽空封装了一个文本框根据输入内容自适应高度的插件,这里推荐给小伙伴们。

autoTextarea.js

(function($){
$.fn.autoTextarea = function(options) {
var defaults={
maxHeight:null,
minHeight:$(this).height()
};
var opts = $.extend({},defaults,options);
return $(this).each(function() {
$(this).bind("paste cut keydown keyup focus blur",function(){
var height,style=this.style;
this.style.height = opts.minHeight + 'px';
if (this.scrollHeight > opts.minHeight) {
if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
height = opts.maxHeight;
style.overflowY = 'scroll';
} else {
height = this.scrollHeight;
style.overflowY = 'hidden';
}
style.height = height + 'px';
}
});
});
};
})(jQuery);

  

demo.js
 $(".doctable textarea").autoTextarea({
maxHeight:400,
minHeight:100
});