LoginSignup
3
3

More than 5 years have passed since last update.

textareaの大きさを自動調整

Last updated at Posted at 2018-10-19

概要

入力量に応じて自動でtextareaのrowsを設定します。前に書いた記事だとうまくいかないことがあったので別の方法を考えました。

使い方

以下の内容を記した関数などをSetIntervalなどで定期的に呼び出すか、keyupイベント等のタイミングで呼び出してください。

自動で拡大する

JQueryを使う場合

const target = $("テキストエリアのIDなど");
const rawTarget = target.get(0);
let lineHeight = Number(target.attr("rows"));
while (rawTarget.scrollHeight > rawTarget.offsetHeight){
    lineHeight++;
    target.attr("rows", lineHeight);
}

JQueryを使わない場合

const target = document.getElementById("テキストアリアのID");
let lineHeight = Number(target.getAttribute("rows"));
while (target.scrollHeight > target.offsetHeight){
    lineHeight++;
    target.setAttribute("rows", lineHeight);
}

最大行数を設定して自動で拡大する

const target = document.getElementById("テキストアリアのIDなど"); //jQueryの場合は target = $("~~").get(0); でOK
const maxLineHeight = 最大行数;
let lineHeight = Number(target.getAttribute("rows"));
while (Target.scrollHeight > Target.offsetHeight && lineHeight < maxLineHeight){
    lineHeight++;
    target.setAttribute("rows", lineHeight);
}
3
3
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
3
3