1 function inputCheck(obj){
2 if (null == event) {
3 event = window.event;
4 }
5 var keyCode = event.keyCode;
6 var key = (keyCode);
7 if( keyCode < 48 && keyCode != 46 || keyCode > 57 ){
8 event.returnValue = false;
9 }
10 var value = $(obj).val();
11 var valueStr = value.toString();
12 var dotPosition = valueStr.indexOf(".");
13 if(keyCode == 46){
14 if(valueStr == ""){
15 event.returnValue = false;
16 }
17 if(dotPosition > -1 ){
18 event.returnValue = false;
19 }
20 }
21 if(dotPosition > -1){
22 var dotLength = valueStr.substr(dotPosition + 1).length;
23 if(dotLength >= 2){
24 var position = getPosition(obj);
25 if(position > dotPosition){
26 event.returnValue = false;
27 }
28 }
29 }
30 }
31 function getPosition(obj){
32 var result = 0;
33 if(obj.selectionStart){ //非IE浏览器
34 result = obj.selectionStart
35 }else{ //IE
36 var rng;
37 if(obj.tagName == "TEXTAREA"){ //如果是文本域
38 rng = event.srcElement.createTextRange();
39 rng.moveToPoint(event.x,event.y);
40 }else{ //输入框
41 rng = document.selection.createRange();
42 }
43 rng.moveStart("character",-event.srcElement.value.length);
44 result = rng.text.length;
45 }
46 return result;
47 }
2 if (null == event) {
3 event = window.event;
4 }
5 var keyCode = event.keyCode;
6 var key = (keyCode);
7 if( keyCode < 48 && keyCode != 46 || keyCode > 57 ){
8 event.returnValue = false;
9 }
10 var value = $(obj).val();
11 var valueStr = value.toString();
12 var dotPosition = valueStr.indexOf(".");
13 if(keyCode == 46){
14 if(valueStr == ""){
15 event.returnValue = false;
16 }
17 if(dotPosition > -1 ){
18 event.returnValue = false;
19 }
20 }
21 if(dotPosition > -1){
22 var dotLength = valueStr.substr(dotPosition + 1).length;
23 if(dotLength >= 2){
24 var position = getPosition(obj);
25 if(position > dotPosition){
26 event.returnValue = false;
27 }
28 }
29 }
30 }
31 function getPosition(obj){
32 var result = 0;
33 if(obj.selectionStart){ //非IE浏览器
34 result = obj.selectionStart
35 }else{ //IE
36 var rng;
37 if(obj.tagName == "TEXTAREA"){ //如果是文本域
38 rng = event.srcElement.createTextRange();
39 rng.moveToPoint(event.x,event.y);
40 }else{ //输入框
41 rng = document.selection.createRange();
42 }
43 rng.moveStart("character",-event.srcElement.value.length);
44 result = rng.text.length;
45 }
46 return result;
47 }
<html>
<input type="text" onkeypress="inputCheck(this);"/>
</html>