To enter content in a textarea, the default is one line. When too much content is entered, the line will automatically wrap and the height will increase?
1, use shadow
<p style="height:0; overflow:hidden;">
<p class="shadow"></p>
</p>
<textarea style="overflow:hidden;"></textarea>
<script>
textarea.addEventListener('input', function(e) {
shadow.innerHTML = this.value.replace(/\</g, '<').replace(/\>/g, '>');
this.height = shadow.clientHeight + 'px';
});
</script>
2, use contenteditable attribute
<p contenteditable="true">這里的高度會隨內(nèi)容自動擴展</p>
3, if using
textarea.style.height = textarea.scrollHeight + 'px';
This form can also adjust the height, but the scroll bar will flash when the line is changed, and the height will only increase but not decrease, which is the worst writing experience.
Give the textarea an oninput event
<textarea id="text"></textarea>
document.getElementById('text').style.height = document.getElementById('text').scrollHeight + 'px'
Similar to this
The total height of the textarea (use jQ’s element.height(), if it is native js, please check the BIF of the manual) / the row height you defined