2016/11/10

[JavaScript][jQuery]テキストエリアを入力内容に応じて自動的に高さを調整

昔書いたかもしれないのですが、忘れてしまったので、改めて。

テキストエリアを入力内容に応じて自動的に高さを調整する方法を調査しました。

qiita 入力内容の量に応じたtextareaの自動サイズ変更
テキストエリアの高さを文字数に応じて変更
を参考にしながら、少しアレンジして、以下のように実装しました。

$('textarea').on('keydown', function (e) {
    if (e.target.scrollHeight > e.target.offsetHeight) {
        $(e.target).height(e.target.scrollHeight);
    }
    else {
        //_textAreaHeight is default height
        var _height = $(e.target).height() - _textAreaHeight;
        if (_height < _textAreaHeight) {
            _height = _textAreaHeight;
        }
        $(e.target).height(_height);
        if (e.target.scrollHeight > e.target.offsetHeight) {
            $(e.target).height(e.target.scrollHeight);
            return;
        }
        else if ($(e.target).height() <= _textAreaHeight) {
            return;
        }
    }
});

0 コメント:

コメントを投稿