Google翻訳のテキストエリアの様に高さがコンテンツの文量に応じて変化する<textarea>を実装します.
HTML
<textarea id="realArea" name="real" rows="15" cols="40"></textarea>
<p id="dummyArea"></p>
ダミーの<p>を用意します.
CSS
textarea#realArea {
width: 50vw;
height: 250px;
font-size: large;
font-family: inherit;
}
p#dummyArea {
margin: 0;
padding: 0;
width: 50vw;
text-align: left;
font-size: large;
font-family: inherit;
visibility: hidden;
}
cssの設定がとても大事です.
- 幅をビューポート単位で本体とダミーが同じになる様にする.
- 同様に
font-sizeも本体とダミーが同じになる様にする.
JavaScript
const realArea = document.getElementById("realArea");
const dummyArea = document.getElementById("dummyArea");
const defaultHeight = 250; // CSSで決めたデフォルトの値と一致させる
window.onload = function() {
realArea.addEventListener("input", function(evt) {
dummyArea.innerHTML = evt.target.value.replace(/\n/g, "<br>") + "<br>";
const newHeight = dummyArea.offsetHeight;
if (newHeight > defaultHeight) {
evt.target.style.height = newHeight + "px";
} else {
evt.target.style.height = defaultHeight + "px";
}
}, false);
}
こんなに短いコードでも驚くほどいい感じに動きます.