有时候在text文本框,texearea中 属性maxlength会不起作用
这时候限制输入的字符串长度并截断,其中字符串(含中英文混合字符串)
如:
<textarea rows="6" id="commentArea" style="width:100%" maxLength="10" οnchange="onchangeSub(this)"></textarea>
<script type="text/javascript">
//计算字符长度,(含中文,英文混合字符)
function CharLength(parameters){
var w=0;
for (var i=0;i<parameters.length; i++) {
var c = parameters.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
w++;
}
else {
w+=2;
}
}
return w;
}
//截取字符串长度(中英文混合字符)
function subString(str,len,hasDot){
var newLength = 0;
var newStr = "";
var chineseRegex = /[^\x00-\xff]/g;
var singleChar = "";
var strLength = str.replace(chineseRegex,"**").length;
for(var i = 0;i < strLength;i++)
{
singleChar = str.charAt(i).toString();
if(singleChar.match(chineseRegex) != null)
{
newLength += 2;
}
else
{
newLength++;
}
if(newLength > len)
{
break;
}
newStr += singleChar;
}
if(hasDot && strLength > len)
{
newStr += "...";
}
return newStr;
}
function onchangeSub(obj)
{
var objValue=obj.value;
var maxlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
var objLength=CharLength(objValue);
if(objLength>maxlength)
{
obj.value=subString(objValue,maxlength);
}
}
</script>
以上是自己在项目中遇到的,就写下咯!