Jquery实现textarea根据文本内容自适应高度
在玩微博的时候我们可能会注意到一个细节就是不管是新浪微博还是腾讯微博在转发和评论的时候给你的默认文本框的高度都不会很高,这可能是版面的限制和用户通常只转播或者评论一个短句有关。但是当你输入超过一行文字的时候,文本框的高度就自动撑高了,大大改善了体验,这样用户就可以看到全部的文字。不用再去拖动文本框的滚动条。
autoTextarea.js
(function($){
$.fn.autoTextarea=function(options){
vardefaults={
maxHeight:null,
minHeight:$(this).height()
};
varopts=$.extend({},defaults,options);
return$(this).each(function(){
$(this).bind("pastecutkeydownkeyupfocusblur",function(){
varheight,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
$(".doctabletextarea").autoTextarea({
maxHeight:400,
minHeight:100
});
以上所述就是本文的全部内容了,希望能够给大家学习jQuery有所帮助。