根据输入内容的长度自动调整文本域的高度

/**
 *  根据输入内容的长度自动调整文本域的高度
 */

/**
 * 
 * @param {被监听的元素, 默认是window} textareaElem 
 * @param {文本域的最小高度, 默认是32} minHeight 
 * @param {文本域的最大高度, 默认是500} maxHeight 
 * 
 */

// adjustTextareaHeight.js

function adjustTextareaHeight(textareaElem = window, minHeight = 32, maxHeight = 500) {
    textareaElem.addEventListener('input', function (e) {
        var tElem = e.target;
        if (tElem.tagName !== 'TEXTAREA') return;
        
        var unit = 'px'
        var diff = tElem.offsetHeight - tElem.clientHeight;
        
        tElem.style.height = 0; // 设置高度为0是为了改变tElem.scrollHeight

        if (tElem.scrollHeight <= minHeight){
            tElem.style.height = minHeight + unit;
        } else if(tElem.scrollHeight >= maxHeight) {
            tElem.style.height = maxHeight + unit;
        } else{
            tElem.style.height = tElem.scrollHeight + diff + unit;
        }

    });

}

使用示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>adjustTextareaHeightDemo</title>
</head>
<body>
    <textarea  style="padding: 10px;" rows="2" cols="40"></textarea>

    <script src="../adjustTextareaHeight.js"></script>
    <script>
        adjustTextareaHeight()
    </script>
</body>
</html>

在页面上的效果:

输入前:

 输入部分内容后文本域自动变长:

 当输入的内容达到最大长度时会显示滚动条:

 删除部分内容后文本域自动变短:

 源码地址: https://github.com/1061186575/JS-Library

原文地址:https://www.cnblogs.com/zp106/p/12305245.html