<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>textarea输入限制</title>
<script type="text/javascript">
function textareaInputLimit(o){
if(!o.maxLength) return;
var maxLength = parseInt(o.maxLength);
var inputLength = o.value.len();
if (inputLength > maxLength){
alert("只能输入" + maxLength + "个字符");
o.value = getByteVal(o.value,maxLength);
}
}
//返回字符串的实际长度, 一个汉字算2个长度
String.prototype.len = function(){
return this.replace(/[^\x00-\xff]/g,"**").length;
}
function getByteVal(val,max){
var returnValue = '';
var byteValLen = 0;
for(var i = 0; i < val.length; i++){
//if (val[i].match(/[^\x00-\xff]/ig) != null){
if (val.charAt(i).match(/[^\x00-\xff]/ig) != null){
byteValLen +=2;
}else{
byteValLen +=1;
}
if (byteValLen > max)
break;
returnValue += val.charAt(i);
}
return returnValue;
}
</script>
</head>
<body>
<textarea maxLength="10" id="textArea" cols="15" rows="15" onkeyup="textareaInputLimit(this)" onkeydown="textareaInputLimit(this)" onchange="textareaInputLimit(this);"></textarea>
</body>
</html>