实时监听textarea并限制最大字符数

直接源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>textarea</title>
    <script type="text/javascript" src="http://libs.useso.com/js/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        function limitTextarea(self,nowleng){
            $(self).on('input propertychange', function(event) {
                var _val = $(self).val();
                _val = _val < 140 ? _val : _val.substr(0,140);
                $(self).val(_val);
                $(nowleng).text(_val.length)
            });
            $(self).blur(function(){
                $(self).off('input propertychange');
            });
        }
    </script>
</head>
<body>
    <textarea maxlength="140" rows="5" class="form-control limit-textarea" onfocus="limitTextarea(this,'.state');"></textarea>
    <p><span class="state">0</span>/140字</p>
</body>
</html>
posted @ 2015-08-07 15:35  木尘-MCDNF  阅读(514)  评论(0编辑  收藏  举报