zoukankan      html  css  js  c++  java
  • 根据输入内容的长度自动调整文本域的高度

    /**
     *  根据输入内容的长度自动调整文本域的高度
     */
    
    /**
     * 
     * @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

  • 相关阅读:
    并发编程(一) 操作系统基础和进程
    操作系统发展史
    网络编程(三) 大文件传输与UDP通信
    网络编程(二)-socket套接字
    网络编程(一)
    排序算法之冒泡法
    第二章 算法基础 思考题2-1
    查找算法之二分查找
    排序算法之归并排序
    排序算法之插入排序
  • 原文地址:https://www.cnblogs.com/zp106/p/12305245.html
Copyright © 2011-2022 走看看