LoginSignup
2

More than 5 years have passed since last update.

jquery で textarea リサイズ

Posted at

自動でテキストエリアリサイズしたい。

以下を jquery.autogrow.min.js で保存



"use strict";!function(a){function b(b,f){if("TEXTAREA"===b.tagName){var g=a(b),h=a("<div></div>");h.addClass(e),void 0!==f.id&&h.attr("id",0==index?f.id:f.id+"-"+index),void 0!==f.classes&&h.addClass(f.classes),g.addClass(d).on("input keyup",function(a){var b=g.val();b&&"\n"!=b.charAt(b.length-1)||(b+=" "),b=b.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ /g,"&nbsp;").replace(/\n/g,"<br/>"),h.html(b),g.height(h.height())}).off(c+".resize").on(c+".resize",function(){h.css({border:g.css("border"),"font-family":g.css("font-family"),"font-size":g.css("font-size"),"font-weight":g.css("font-weight"),"letter-spacing":g.css("letter-spacing"),"line-height":g.css("line-height"),padding:g.css("padding"),position:"absolute",visibility:"hidden","white-space":"normal",width:g.css("width"),"word-break":"break-word","z-index":-1,zoom:g.css("zoom")})}).trigger(c+".resize").after(h)}}var c="autogrow",d=c+"-field",e=c+"-mirror";a.fn[c]=function(c,d){var e=this,f=this.context;return void 0===d&&(d=c instanceof Object?c:{}),"string"!=typeof c&&(c=null),c&&(e=a(c,f),a(document).on("DOMNodeInserted",function(e){var g=e.target;a(g,f).is(c)&&b(g,d)})),e.each(function(a,c){b(c,d)}),this}}(jQuery);


で適当に読み出す。

$(textarea).autogrow();

で自動的にテキストエリアが伸びる。

最初からテキストを入れてある場合は、

$(textarea).trigger('keyup');

とすれば最初に入っているテキストエリアの高さに自動調整される。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2