自動サイズ変更機能付きテキストエリアの作成 質問する

自動サイズ変更機能付きテキストエリアの作成 質問する

ありましたこれについての別のスレッド、試してみました。しかし、問題が 1 つあります。textareaコンテンツを削除しても は縮小されません。正しいサイズに縮小する方法が見つかりません。値は のコンテンツではなく、clientHeightのフル サイズとして返されますtextarea

そのページのコードは以下のとおりです。

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}

ベストアンサー1

完全かつシンプルなソリューション

2023-06-08 更新(js インジェクションによる更新用のネイティブ js を追加)

次のコードは機能します:

  • キー入力時。
  • 貼り付けられたテキスト(右クリック & Ctrl+V)。
  • 切り取ったテキスト付き(右クリック & Ctrl+X)。
  • テキストがあらかじめロードされています。
  • サイト全体のすべてのテキストエリア(複数行テキストボックス)を使用します。
  • Firefox (v31-109 テスト済み)を使用。
  • Chrome を使用(v37-108 でテスト済み)。
  • IE (v9-v11 テスト済み)を使用。
  • Edge を使用(v14-v108 でテスト済み)。
  • IOS Safariの場合。
  • Android ブラウザを使用。
  • JavaScript厳密モードを使用します。

オプション 1 (jQuery を使用)

このオプションにはjQuery1.7.2 - 3.6.3でテスト済みで動作しています

シンプル (この jQuery コードをマスター スクリプト ファイルに追加して、あとは忘れてください。)

$("textarea").each(function () {
  this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
}).on("input", function () {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.3.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test on jsfiddle


オプション 2 (純粋な JavaScript)

シンプル (この JavaScript をマスター スクリプト ファイルに追加して、あとは忘れてください。)

const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + "px";
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Test on jsfiddle


オプション 3 (jQuery 拡張)

テキストエリアにさらにチェーンを適用し、サイズを自動調整したい場合に便利です。

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ "height": 0, "overflow-y": "hidden" })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on("input", function() {
        autoHeight_(this);
      });
    });
  }
});

呼び出し$("textarea").autoHeight()


JavaScript によるテキストエリアの更新

JavaScript 経由でテキストエリアにコンテンツを挿入する場合は、次のコード行を追加してサイズ変更機能を呼び出します。

jQuery

$("textarea").trigger("input");

純粋なJavaScript

document.getElementsByTagName("textarea")[0].dispatchEvent(new Event('input', { bubbles: true }));

テキストエリアの高さをプリセット

テキストエリアの初期の高さを固定するには、別の条件を追加する必要があります。

const txHeight = 16;
const tx = document.getElementsByTagName("textarea");

for (let i = 0; i < tx.length; i++) {
  if (tx[i].value == '') {
    tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;");
  } else {
    tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  }
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput(e) {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + "px";
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

おすすめ記事