CSS 中,使用 JavaScript 自動增長文字區域


使用 JavaScript,我們可以設定 TextArea 元素,使其隨著內容自動增長。以下示例說明了如何實現上述場景。假設在新增內容之前,以下內容是我們的 TextArea −

以下是在新增內容後顯示的 TextArea −

以下是相同的 TextArea,在新增更多內容後自動增長 −

自動增長文字域

示例

讓我們看看如何自動增長文字域 −

<!DOCTYPE html>
<html>
<head>
   <style>
      * {
         margin: 3%;
         color: navy;
         font-size: 1.2em;
      }
      #ta {
         padding: 2%;
         resize: none;
         width: 330px;
         min-height: 80px;
         overflow: hidden;
         box-sizing: border-box;
      }
   </style>
</head>
<body>
   <form>
   <label for="ta">Cool TextArea</label>
   <textarea id="ta"></textarea>
   </form>
   <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
   <script>
      $("#ta").on('input', function() {
         var scroll_height = $("#ta").get(0).scrollHeight;
         $("#ta").css('height', scroll_height + 'px');
      });
   </script>
</body>
</html>

使用滾動機制自動增長文字域

示例

我們在這裡設定滾動時使用值為 scrolloverflow-y 屬性 −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin: 3%;
         overflow-y: scroll;
      }
      #ta {
         padding: 2%;
         resize: none;
         width: 333px;
         min-height: 90px;
         overflow: hidden;
         box-sizing: border-box;
         font-size: 1.5em;
      }
   </style>
</head>
<body>
   <div>
      <textarea id="ta"></textarea>
   </div>
   <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
   <script>
      $("#ta").on('input', function() {
         var scroll_height = $("#ta").get(0).scrollHeight;
         $("#ta").css('height', scroll_height + 'px');
      });
   </script>
</body>
</html>

更新於: 27-Oct-2023

405 次瀏覽

開啟你的職業

完成課程後即可獲得認證

課程開始
廣告
© . All rights reserved.