JavaScript在ASP页面中实现掩码文本框效果代码

2019-01-13 02:40:06于丽


  if (strText.match(expMask))
  {
  // 输入格式正确
  objTextBox.value = strText;
  }
  最后将光标移到适当的位置。
  
  // 移动光标
  setCursor(objTextBox,nCursorPos);

  完成!
  其主要就是把系统的键盘消息替换成自己的处理,屏蔽掉系统的,这样就可以获得最大的操控。
  如此就完成了一个对指定的正则表达式进行格式限制的TEXTBOX就诞生了。
  

  // 根据指定正表达式,来控制OBJ表示
  function mask(objTextBox,mask)
  {
  // 掩码
  expMask = new RegExp(mask);
  // 当前文本框中的文本
  var strText =objTextBox.value;
  // 文本长度
  var nTextLen=strText.length;
  // 当前光标位置
  var nCursorPos=getPos(objTextBox);
  // 按下的键码
  var nKeyCode = window.event.keyCode;
  if (nKeyCode > 95) nKeyCode -= (95-47);
  // 封住传统处理
  window.event.returnvalue = false;
  // 自行处理按钮
  switch (nKeyCode)
  {
  case 8:// 如果动作是退格[<-]
  {
  strText = strText.substr(0,nCursorPos-1) + strText.substr(nCursorPos, nTextLen-nCursorPos);
  nCursorPos--;
  break;
  }
  case 46:// 如果动作是del[del]
  {
  strText = strText.substr(0,nCursorPos) + strText.substr(nCursorPos+1,nTextLen-nCursorPos-1);
  nCursorPos--;
  break;
  }
  case 38:// 如果动作是方向键[上]
  case 39:// 如果动作是方向键[右]
  {
  nCursorPos++;
  break;
  }
  case 37:// 如果动作是方向键[左]
  case 40:// 如果动作是方向键[下]
  {
  nCursorPos--;
  break;
  }
  default :
  {
  strText = strText.substr(0,nCursorPos) + String.fromCharCode(nKeyCode) + strText.substr(nCursorPos,nTextLen);
  nCursorPos++;
  if (nCursorPos>strText.length)
  {
  nCursorPos=strText.length;
  }
  break;
  }
  }
  if (strText.match(expMask))
  {
  // 输入格式正确
  objTextBox.value = strText;
  }
  // 移动光标
  setCursor(objTextBox,nCursorPos);
  }
  // 得到一个文本框控件的当前光标位置
  function getPos(obj)
  {
  obj.focus();
  var workRange=document.selection.createRange();
  obj.select();
  var allRange=document.selection.createRange();
  workRange.setEndPoint("StartToStart",allRange);
  var len=workRange.text.length;
  workRange.collapse(false);
  workRange.select();
  return len;
  }
  // 设置一个文本框控件的当前光标位置
  function setCursor(obj,num){
  range=obj.createTextRange();
  range.collapse(true);
  range.moveStart('character',num);
  range.select();
  }