跳转至

实现HTML中的textarea元素自适应高度

js函数内容

function.js
1
2
3
4
5
6
/*textarea 自适应高度*/
function autoResize(id) {
    const textArea = document.getElementById(id);
    textArea.style.height = "auto";
    textArea.style.height = (textArea.scrollHeight) + "px";
}

使用方法

<textarea id="my-textarea" oninput="autoResize('my-textarea')"></textarea>
<script type="text/javascript">
    function autoResize(id) {
        const textArea = document.getElementById(id);
        textArea.style.height = "auto";
        textArea.style.height = (textArea.scrollHeight) + "px";
    }
</script>

示例

评论