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