现在的位置: 首页 > 综合 > 正文

onKeypress对中文无效

2012年03月01日 ⁄ 综合 ⁄ 共 1018字 ⁄ 字号 评论关闭

今天想在javascript中限制输入长度,使用如下的代码:
<html>
<body>
<input type="textbox" onKeypress="Javascript:zlk(5);" />
<script type="text/javascript">
function zlk(lSize)
{
  if (event.srcElement.value.truelen()>lSize)
  { //长度超出时,取消输入
    event.keyCode=0;
  }
}
String.prototype.truelen=function()
{
  var i=0;
  for (var j=0;j<this.length;j++)
  {
    if (this.charCodeAt(j)>255)
      i+=2;
    else
      i++;
  }
  return i;
}
</script>
</body>
</html>
结果发现对数字、英文都工作得很好,但对中文却不行,根本不会激发onKeypress事件。以为IE的BUG,后来找到另一个事件onpropertychange来处理,代码改为如下:
<html>
<body>
<input type="textbox" onpropertychange="Javascript:zlpc(5);"/>
<script type="text/javascript">
var lastValue="";
function zlpc(lSize)
{
 //debugger;
 if (event.propertyName=="value")
  if (event.srcElement.value.truelen()>lSize)
  { //长度超出时,取消输入
   //event.returnValue=false; //这种取消事件的方法没有效果
   //只好用恢复原值的方法
   event.srcElement.value=lastValue;
  }
  else
   lastValue=event.srcElement.value;
}

String.prototype.truelen=function()
{
  var i=0;
  for (var j=0;j<this.length;j++)
  {
    if (this.charCodeAt(j)>255)
      i+=2;
    else
      i++;
  }
  return i;
}
</script>
</body>
</html>

抱歉!评论已关闭.