有时在开发中会遇到要求textarea多行文本输入时高度自适应,不废话直接上代码:
HTML
<textarea name="textArea" id="textarea"></textarea>
JS
(function(){ var textArea = document.getElementById('textarea'); function activeGo() { var scrollHeight = textArea.scrollHeight; var height = textArea.offsetHeight; if(height < scrollHeight){ var row = textArea.getAttribute('rows'); var newRow = parseInt(row) + 1; textArea.setAttribute('rows', newRow); // textArea.style.height = textArea.scrollHeight+'px'; } } textArea.addEventListener('propertychange',activeGo); textArea.addEventListener('input',activeGo); })();