Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@SoundRabbit

textareaの大きさを自動調整

概要

入力量に応じて自動で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);
}
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
1
Help us understand the problem. What are the problem?