js判断文本长度(中英文)

效果如图,可以把代码复制到编辑器另存为test.html,用浏览器打开即可看到效果。

<script type="text/javascript">
String.prototype.trim = function()
{
	return this.replace(/(^\s*)|(\s*$)/g, "");
}
 
function checkWord(evt)
{
	var overFont=document.getElementById("overFont");
	if(evt==null)
	{
		evt = 	window.event;
	}
	var src = 	evt.srcElement? evt.srcElement : evt.target;
	var str	=	src.value;
	len		=	160;
	myLen	=	0;
	i		=	0;
	Other	=	70;
	for(;(i<str.length)&&(myLen<=len);i++)
	{
		myLen++;
		if(str.charCodeAt(i)<0||str.charCodeAt(i)>128)
		{
			len=Other;
		}
	}
	if(myLen>len)
	{
		alert("您输入超过限定长度");
		src.value=str.substring(0,i-1);
	}
	if(len-myLen>0)
	{
		overFont.innerHTML="您还能输入"+(len-myLen)+"个字";
	}
	else
	{
		overFont.innerHTML="还剩"+0+"个字";
    }
}
</script>
<textarea id="messageContent" onkeyup="javascript:checkWord(event)" cols="75" rows="3" name="messageContent"></textarea>
<div class="gray">
<font id="overFont"></font>
</div>

Related posts:

Leave a Reply

Your email address will not be published.