使用JavaScript建立自動調整大小的文字區域


在這篇文章中,我們將學習如何在JavaScript中設定一個自動調整大小的文字區域。這個文字區域能夠根據其中的內容自動改變其高度。JavaScript中的自動調整大小文字是一個有用的功能,可以用於編輯多行文字。文字可以根據其內部內容自動更改其高度。文字區域的預設行為不允許這樣做,但是我們可以透過在其上使用input事件監聽器來建立它。

讓我們透過一些示例瞭解如何動態調整文字區域元素的高度:

示例1

在本例中,我們將:

  • 使用ID選擇文字區域並新增input事件監聽器。

  • 當用戶調整文字大小時,我們首先將文字高度設定為滾動高度,然後將文字高度設定為auto(預設),最後根據內容調整文字高度。

檔名 - index.html

<html>
<head>
   <title>Creating auto-resize text area using JavaScript</title>
   <style>
      #container {
         width: 310px;
      }

      textarea {
         width: 100%;
         resize: none;
         overflow: hidden;
      }
   </style>
</head>
<body>
   <h3>Auto-resize Text Area</h3>
    
   <div id="container">
      <textarea id="myTextArea" rows="1" placeholder="Enter text..."></textarea>
   </div>

   <script>
      const textArea = document.getElementById("myTextArea");

      textArea.addEventListener("input", function () {
         this.style.height = "auto";
         this.style.height = this.scrollHeight + "px";
      });
   </script>
</body>
</html>

輸出

結果將如下圖所示。

示例2

在這個例子中,我們將:

  • 定義一個resizeTextArea()函式,該函式在input事件發生時和resize事件發生時(視窗大小調整時)都會被呼叫。

  • 這樣做的目的是為了在使用者在鍵入時調整視窗大小的情況下保持文字區域的正確高度。

檔名 - index.html

<html>
<head>
   <title>Creating auto-resize text area using JavaScript</title>
   <style>
      #container {
         width: 310px;
      }

      textarea {
         width: 100%;
         resize: none;
         overflow: hidden;
      }
   </style>
</head>
<body>
   <h3>Auto-resize Text Area</h3>

   <div id="container">
      <textarea id="myTextArea" rows="1" placeholder="Enter text..."></textarea>
   </div>

   <script>
      const textArea = document.getElementById("myTextArea");

      function resizeTextArea() {
         textArea.style.height = "auto";
         textArea.style.height = textArea.scrollHeight + "px";
      }

      textArea.addEventListener("input", resizeTextArea);
      window.addEventListener("resize", resizeTextArea);
   </script>
</body>
</html>

輸出

結果將如下圖所示。

結論

總之,使用JavaScript的自動調整大小文字區域功能為處理多行文字輸入和根據內部內容更改文字區域的高度提供了使用者友好的體驗。透過使用事件監聽器和DOM操作,我們能夠建立一個自動調整大小的文字區域。我們學習了使用JavaScript自動調整大小文字區域的概念,並透過一些示例進行了說明。

更新於:2023年8月16日

703 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.