0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascript:<textarea>の文量に応じた自動高さ変更

Last updated at Posted at 2019-02-17

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

こんなに短いコードでも驚くほどいい感じに動きます.

0
2
0

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?