64
45

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.

textareaを改行に応じて自動で高さが変わるようにする方法

Last updated at Posted at 2018-05-02

入力イベント時に、テキストエリア内の文字の行高さ×改行文字数でheightを変えてやることで実装できます。
高さの最大限を指定したい場合は単純にmaxHeightを指定すればOKです。

サンプルコード

<textarea id="textarea" placeholder="改行で高さが変わる"></textarea>
#textarea {
  width: 200px;
  max-height: 200px;
  padding: 8px;
  line-height: 20px;
}
$(function() {
  var $textarea = $('#textarea');
  var lineHeight = parseInt($textarea.css('lineHeight'));
  $textarea.on('input', function(e) {
    var lines = ($(this).val() + '\n').match(/\n/g).length;
    $(this).height(lineHeight * lines);
  });
});

動作デモ(jsfiddle)

こちらからご覧ください
https://jsfiddle.net/maiko_ampersand/8asbLrn9/

64
45
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
64
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?