昨天做了个测试onkeypress 检测输入的数据 先记录下
可惜只有IE支持ime-mode:disabled
function checkInputNumber(ele,checkType,maxPoint){
ele.onkeypress = function(e){
var e = e || window.event,
charCode = typeof e.charCode == "number" ? e.charCode : e.keyCode;
if(checkType == "voucherNumber"){ //数字
if(!/\d/.test(String.fromCharCode(charCode)) && charCode > 9){
preventDefault(e);
}
}
else if(checkType == "amount"){ //金额 maxPoint为保留的小数位数
if( (!/\d/.test(String.fromCharCode(charCode)) && charCode != 46) || (charCode == 46 && ele.value.indexOf(".") > -1) ||
/\d/.test(String.fromCharCode(charCode)) && ele.value.indexOf(".") > -1 && (ele.value.indexOf(".") + 1 + maxPoint) == ele.value.length && getCursortPosition(ele) > ele.value.indexOf(".")){
if(charCode > 9){
preventDefault(e);
}
}
}
};
ele.onpaste = function(){
preventDefault(e);
}
}
function preventDefault(e){
if(e.preventDefault){
e.preventDefault();
}else{
window.event.returnValue = false;
}
}
function getCursortPosition (ele) {//获取光标位置函数
var cursorPos = 0; // IE Support
if (document.selection) {
ele.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ele.value.length);
cursorPos = Sel.text.length;
}
// Firefox support
else if (ele.selectionStart || ele.selectionStart == '0')
cursorPos = ele.selectionStart;
return cursorPos;
}
checkInputNumber(document.getElementById("voucherNumber"),"voucherNumber");
checkInputNumber(document.getElementById("amountId"),"amount",2);