js 限制input輸入字節長度


<script>
function WidthCheck(str, maxLen){ 
    var w = 0; 
    var tempCount = 0; 
    //length 獲取字數數,不區分漢子和英文 
    for (var i=0; i<str.value.length; i++) { 
        //charCodeAt()獲取字符串中某一個字符的編碼 
        var c = str.value.charCodeAt(i); 
        //單字節加1 
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
            w++; 
        } else { 
            w+=2; 
        } 
        if (w > maxLen) { 
            str.value = str.value.substr(0,i); 
            break; 
         } 
    } 
} 
</script> 
<input type="text" id="nickname" class="nickname" value="" onkeyup="WidthCheck(this,8);"/>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM