textarea高度自适应

var $textarea = document.getElementById('textarea0');
           console.log($textarea)
          var lastLength = 0;
          var lastHeight = 0;
          $textarea.addEventListener('input', function() {
              var currentLength = $textarea.value.length;
              // 判断字数如果比之前少了,说明内容正在减少,需要清除高度样式,重新获取
              if (currentLength < lastLength) {
                  $textarea.style.height = '';
              }
              var currentHeight = $textarea.scrollHeight;
              // 如果内容高度发生了变化,再去设置高度值
              if (lastHeight !== currentHeight || !$textarea.style.height) {
                  $textarea.style.height = currentHeight + 2 + 'px';
              }
              lastLength = currentLength;
              lastHeight = currentHeight;
          });

  

原文地址:https://www.cnblogs.com/love314159/p/14344083.html