自身属性:maxlength="10" 设置字数,英文跟中文字数一样
JS解决方案:
$('#demo').on('keyup',function(){
var str = document.getElementById('memo').value;
GetCharLength(str);
});
//获取字符串的字节长度
function GetCharLength(str){
var iLength = 0; //记录字符的字节数
for(var i = 0;i<str.length;i++)//遍历字符串中的每个字符
{
if(str.charCodeAt(i) >255) //如果当前字符的编码大于255
{
iLength += 2; //所占字节数加2
}else{
iLength += 1; //否则所占字节数加1
}
if(iLength > 10){//设置的字符限制数
document.getElementById('memo').value = str.substring(0,i); //截取字符return;
}
}
}
var str = '啊';
var num = str.charCodeAt(0);//通过charCodeAt()码转成数字 如果要限制中文,则大于255
alert(String.fromCharCode(num));//通过fromCharCode()转成字符