LoginSignup
5
5

More than 5 years have passed since last update.

[Angular.js]縦方向だけ自動リサイズしてくれるtextareaのdirective

Posted at

Slackのようなチャットサービスに使われる、文字が増えると縦方向に自動リサイズしてくれるtextareaのdirective。

resizeTextarea.js
app.directive('resizeTextarea', function() {
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    template: "<textarea placeholder='入力してください'></textarea>",
    link: function(scope, element, attrs) {
      var HEIGHT = 25;
      var el = angular.element(element[0])
      el.css('lineHeight', HEIGHT + "px");
      el.css('height', HEIGHT + "px");

      var resize = function(e) {
        var textHeight = e.target.scrollHeight;
        var height = ~~(textHeight / HEIGHT) * HEIGHT
        el.css('height', height + "px");
      };
      el.on('input', resize);
    }
  }
});

使い方

repalceをtrueにしているので以下のように書くと自動でtextareaに置換してくれる。

index.html
<div>
    <resize-textarea></resize-textarea>
</div>
5
5
2

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
5
5