[置顶] JS全角转半角

时间:2022-03-24 09:10:54

一、用JS把全角转换成半角(不能转换标点符号)
 <input type="text" size="10" maxlength="10"
 onkeyup="javascript:var t = ''; with(this.value) { for (var i = 0; i < length; i++) t += (65296 <=charCodeAt(i) &&charCodeAt(i) <= 65305) ? String.fromCharCode(charCodeAt(i) - 65248) : charAt(i); } this.value = t;" />
 <br>
 <br>

二、用JS把全角转换成半角的函数
 <textarea name="n" type="text" id="n" onkeyup="CtoH(this);" style="width:100%;height:100%;"></textarea>
 <SCRIPT>
 function CtoH(obj){
  var str=obj.value;
  var result="";
  for (var i = 0; i < str.length; i++){
   if (str.charCodeAt(i)==12288){
    result+= String.fromCharCode(str.charCodeAt(i)-12256);
    continue;
   }
   if (str.charCodeAt(i)>65280 && str.charCodeAt(i)<65375) result+= String.fromCharCode(str.charCodeAt(i)-65248);
   else result+= String.fromCharCode(str.charCodeAt(i));
  }
  obj.value=result;
 }
 </SCRIPT>
 <BR>
 <BR>

三、用JS把全角转换成半角(只允许输入数字、小数点与负号)


ime-mode:Disabled  关闭输入法

 <input
   onkeypress="var k=event.keyCode; return k>=48&&k<=57||k==46||k==45"
   onpaste="return !clipboardData.getData('text').match(/\D/)"
   ondragenter="return false" style="ime-mode:Disabled"
 >
 <br>
 <br>

四、用JS把全角转换成半角(只允许输入数字)
 <input
   onkeypress="var k=event.keyCode; return k>=48&&k<=57"
   onpaste="return !clipboardData.getData('text').match(/\D/)"
   ondragenter="return false" style="ime-mode:Disabled"
 >
 <br><br>

五、不允许输入全角字符
 <INPUT name="CardId" onKeyUp="quanjiao(this);">
 <script language="javascript">
 function quanjiao(obj){
   var str=obj.value;
   if (str.length>0){
     for (var i = str.length-1; i >= 0; i--){
       unicode=str.charCodeAt(i);
       if (unicode>65280 && unicode<65375){
         alert("不能输入全角字符,请输入半角字符");
         obj.value=str.substr(0,i);
       }
     }
   }
 }


作者:水木     出处:http://www.hitidc.com/