• input限制字符长度


    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>demo</title>
    </head>
    <body>
        <input id="text" placeHolder="最大支持12个字节" maxlength="12" />
        <script type="text/javascript">
         var Str = {
             byteLen : function (str){
                //正则取到中文的个数,然后len*count+原来的长度。不用replace
                str += '';
                var tmp = str.match(/[^x00-xff]/g) || [];
                return str.length + tmp.length;
            },
            getMaxlen : function(str,maxlen){
                var sResult = '', L=0, i=0, stop = false, sChar;
                if(str.replace(/[^x00-xff]/g,'xxx').length <= maxlen){
                    return str;
                }
                while(!stop){
                    sChar = str.charAt(i);
                    L+= sChar.match(/[^x00-xff]/) ? 2 : 1;
                    if(L > maxlen){
                        stop = true;
                    }else{
                        sResult+=sChar;
                        i++;
                    }
                }
                return sResult;
            }
        };
        var inputLock = false;
        document.querySelector('#text').addEventListener('compositionstart', function(){
            inputLock = true;
        })
        document.querySelector('#text').addEventListener('compositionend', function(){
            inputLock = false;
            var value = this.value,
                maxlength = this.getAttribute('maxlength');
            if(Str.byteLen(value) > maxlength){
                this.value = Str.getMaxlen(value, maxlength);
            }
        })
        document.querySelector('#text').addEventListener('input', function(){
            if(!inputLock){
                var value = this.value,
                    maxlength = this.getAttribute('maxlength');
                if(Str.byteLen(value) > maxlength){
                    this.value = Str.getMaxlen(value, maxlength);
                }
            }
        });
        </script>
    </body>
    </html>
  • 相关阅读:
    HTML5 拖放(Drag 和 Drop)详解与实例
    JS中的六大数据类型
    关于创建本地docker仓库
    关于使用国内dock仓库,网易、DaoCloud
    关于Docker开通远程访问端口2375
    多个消费者监听同一个队列
    SQLite -附加数据库
    解密JDK8 枚举
    LoraLU
    深入理解display属性
  • 原文地址:https://www.cnblogs.com/jkr666666/p/11173424.html
Copyright © 2020-2023  润新知