本文給大家分享的是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
- });
以上所述就是本文的全部內容了,希望能夠給大家學習jQuery有所幫助。
新聞熱點
疑難解答
圖片精選