输入框中只能输入数字,小数点,负号
function checkValue(val){ this.val=val;} var discountValue=new checkValue("");//定义全局变量,记录上一次合法的值function clearNoNum(obj,isMinus,objValue){var key = event.keyCode;var value = obj.value;//定义合法按键列表,包括小键盘区0-9,主键盘区0-9,小数点,负号,上下左右方向键,home,end,deletevar mayKey =new Array(8,35,36,37,38,39,40,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110,190);if((key==189||key==109)&&isMinus&&objValue.val.length==0){//根据isMinus判断是否能输入负号,如果可以判断负号是否在第一位objValue.val = value;return false;}for(var i=0;i<mayKey.length;i++){if(key==mayKey[i]){objValue.val = value;return false;}}document.execCommand('undo');//如果键盘点击的不是以上按钮,则清空输入框的值obj.value = objValue.val;//将全局变量的值赋给输入框。即将上一次合法的值重新赋给输入框}function discountCheck(obj){clearNoNum(obj,false,discountValue);}
<input type="text" onkeyup="discountCheck(this)" />