122
108

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Facebookみたいに改行に合わせて伸びるフォーム

Last updated at Posted at 2016-04-14

ググったらなんか無駄に複雑にサンプル多かったんだけど、これでいいじゃんって感じで落ち着いた。

var el = document.querySelector("textarea.your-text-area")
el.addEventListener("input", function(ev) {
  if (parseInt(el.rows, 10) < 8) {
    const currentRow = el.value.split("\n").length;
    el.rows = currentRow + 1;
  }
});

3行目で8行以上多くならないようにしてある。Githubのフォームがこんな仕様だったので真似した。無限に伸ばしたかったら外せば良い。

jQueryは必要ないです。

追記

よく考えたら折り返し考慮してなかったので、もっかい考える。

追記

こうなった

function fitToContent(el, maxHeight) {
  let adjustedHeight = el.clientHeight;
  if ( !maxHeight || maxHeight > adjustedHeight ) {
    adjustedHeight = Math.max(el.scrollHeight, adjustedHeight);
    if ( maxHeight ) {
      adjustedHeight = Math.min(maxHeight, adjustedHeight);
    }
    if ( adjustedHeight > el.clientHeight ) {
      el.style.height = adjustedHeight + "px";
    }
  }
}
el.addEventListener("input", _ev => {
  fitToContent(el, 180);
});
122
108
1

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
122
108

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?