限制textarea输入框可输入的字数

2019-07-12  本文已影响0人  zkzhengmeng
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>textarea 限制字数</title>
    <style>
        .container{
            position: relative;
            width: 730px;
        }
        .container span{
            position: absolute;
            bottom: 20px;
            right: 30px;
        }
    </style>
</head>
<body>
    <div class="container">
        <textarea name="content" id="content" cols="100" rows="10"></textarea>
        <span>0/200</span>
    </div>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
    <script>
        $(function(){
             /**
             * textarea 限制输入字数
             * @param  string str 类名或ID
             * @param  number num 限制输入的字数
             */
            function limitImport(str,num){
                $(document).on('input propertychange',str,function(){
                    var self = $(this);
                    var content = self.val();
                    if (content.length > num){
                        self.val(content.substring(0,num));
                    } 
                    self.siblings('span').text(self.val().length+'/'+num);
                });
            }

            //用法示例
            limitImport('#content',200);

        })
    </script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读