方法一:
<html>
<head><title>text 数字</title>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>
<script type="text/javascript">
function check(event) {
var e = window.event || event;
var target = e.srcElement || e.target;
var k = e.keyCode;
if(isFunKey(k)) {
return true;
}
var c = getChar(k);
if(target.value.length == '' && (c == '-' || c == '+')) {
return true;
}
if(isNaN(target.value + getChar(k))) {
return false;
}
return true;
}
function isFunKey(code) {
// 8 --> Backspace
// 35 --> End
// 36 --> Home
// 37 --> Left Arrow
// 39 --> Right Arrow
// 46 --> Delete
// 112~123 --> F1~F12
var funKeys = [8, 35, 36, 37, 39, 46];
for(var i = 112; i <= 123; i++) {
funKeys.push(i);
}
for(var i = 0; i < funKeys.length; i++) {
if(funKeys[i] == code) {
return true;
}
}
return false;
}
function getChar(k) {
if(k >= 48 && k <= 57) {
return String.fromCharCode(k);
}
if(k >= 96 && k <= 105) {
return String.fromCharCode(k - 48);
}
if(k == 110 || k == 190 || k== 188 ) {
return ".";
}
if(k == 109 || k == 189) {
return "-";
}
if(k == 107 || k == 187) {
return "+";
}
return "#";
}
</script>
<style type="text/css">
textarea {
width: 200px;
height: 80px;
}
span {
color: #ff0000;
}
</style>
<body>
<input style="ime-mode:disabled;" οnpaste="return false" οnkeydοwn="return check(event)" οnkeyup="if(isNaN(this.value)||this.value<0||this.value>59) this.value='0'">
</body>
</html>
方法二:
<input name="Price" value="" class="text" style="width:100px;" οnkeyup="value=value.replace(/[^\d.]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d.]/g,''))" />
后台判定的话要勇正则表达式:
str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");