js根据输入字符长度自动调整textarea高度

1.编写html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自动扩展文本框高度</title>
    <script type="text/javascript" src="../js/jquery.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#words").on("input propertychange",function(e){
                var target = e.target;
                var dh = $(target).attr('defaultHeight') || 0;
                if (!dh) {
                    dh = target.clientHeight;
                    $(target).attr('defaultHeight', dh);
                }

                target.style.height = dh + 'px';
                var clientHeight = target.clientHeight;
                var scrollHeight = target.scrollHeight;
                if (clientHeight !== scrollHeight) {
                    target.style.height = scrollHeight + 10 + "px";
                }
            });
        });

    </script>
</head>
<body style="text-align: center">
    <label><h3>请输入:</h3></label><br>
    <textarea id="words" name="words" style="width: 300px;height: 30px;" default-height="20px"></textarea>
</body>
</html>


2.调试


2.1绑定函数前效果



2.2绑定函数后效果











posted @ 2018-03-07 11:24  一锤子技术员  阅读(4)  评论(0编辑  收藏  举报  来源