input实时监控输入字数,完美解决

该博客介绍了如何实现对input元素的实时字数监控,完美解决了拼音输入和空格输入导致字数变化的问题,提供了一种有效的解决方案。
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <title></title>
    </head>
    <body>
    <textarea  style="resize:none" name="text" id="txt" cols="30" rows="10"></textarea>
    <span class="title2 hide"><span>0</span>/10</span>
    <script>
        var flag = true;
        $('#txt').on('compositionstart',function(){
            flag = false;
        })
        $('#txt').on('compositionend',function(){
            flag = true;
        })
        $('#txt').on('input',function(){
            setTimeout(function(){
                if(flag){
                    var num = $("#txt").val().replace(/\s+/g,"").length;
                    if(num<10){
                        $("#txt").removeAttr("maxlength");
                        $(".title2").html('<span>'+num+'</span>' + '/10');
                    }
                    else{           
                        $(".title2 span").text(num);           
                        $("#txt").attr("maxlength",10);
                    }
                }
            },0)
        })
    </script>
    </body>

</html>

其中 style="resize:none" 起固定作用,可根据需求删除

解决了拼音输入改变字数、空格输入等问题

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值