textareaの大きさを自動調整

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); 
} 

コメント