Jquery实现 TextArea 文本框根据输入内容自动适应高度

原文 Jquery实现 TextArea 文本框根据输入内容自动适应高度html

在玩微博的时候咱们可能会注意到一个细节就是无论是新浪微博仍是腾讯微博在转发和评论的时候给你的默认文本框的高度都不会很高,这多是版面的限制和用户一般只转播或者评论一个短句有关。可是当你输入超过一行文字的时候,TextArea自动适应高度,大大改善了体验,这样用户就能够看到所有的文字。不用再去拖动文本框的滚动条。jquery

 

以下图:this

 

这些在平时的项目中挺实用的,因此抽空封装了一个文本框根据输入内容自适应高度的插件 - TextAreaspa

 

咱们来看看代码:插件

jquery代码:htm

(function($){get

$.fn.autoTextarea = function(options) {io

var defaults={微博

maxHeight:null,//文本框是否自动撑高,默认:null,不自动撑高;若是自动撑高必须输入数值,该值做为文本框自动撑高的最大高度ast

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);

 

调用代码:

$(".chackTextarea-area").autoTextarea({
        maxHeight:220,//文本框是否自动撑高,默认:null,不自动撑高;若是自动撑高必须输入数值,该值做为文本框自动撑高的最大高度
    })

DEMO页面:http://www.yuzi.me/Demo/autoTextArea.html

相关文章
相关标签/搜索