Help us understand the problem. What is going on with this article?

textareaの大きさを自動調整

More than 1 year has passed since last update.

概要

入力量に応じて自動で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);
}
SoundRabbit
20歳JD(情報理工学域大学生)です。Webプログラマー(笑)をしています。符号化理論とかコンピュータアーキテクチャとかを勉強しています。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした