JS onkeydown控制HTML Input 只录入浮点数值

// -1)
return false;

return index == 0
}

keychar = String.fromCharCode(keynum)
var newVal = oriVal.substr(0, index) + keychar + oriVal.substr(index, oriVal.length - index);
console.log(newVal)
var pattern = /^([-]){0,1}([0-9]){1,}([.]){0,1}([0-9]){0,}$/;
return pattern.test(newVal);
}
// ]]>

<script type="text/javascript">

//获取当前光标位置

function getCursortPosition(ctrl) {

var CaretPos = 0;   // IE Support

if (document.selection) {

ctrl.focus();

var Sel = document.selection.createRange();

Sel.moveStart('character', -ctrl.value.length);

CaretPos = Sel.text.length;

}

// Firefox support

else if (ctrl.selectionStart || ctrl.selectionStart == '0')

CaretPos = ctrl.selectionStart;

return (CaretPos);

}

//只录入浮点数

function onlyNumbers(e) {

var keynum

var keychar

var numcheck

if (window.event) // IE

{

keynum = e.keyCode

}

else if (e.which) // Netscape/Firefox/Opera

{

keynum = e.which

}

//Backspace Left Right Delete Key 直接放过

if (keynum == 8 || keynum == 37

|| keynum == 39 || keynum == 46)

{

return true;

}

//减号

var minusCharCode = 189;

//点

var pointCharCode = 190;

var inputCtrl = document.getElementById("mc");

var index = getCursortPosition(inputCtrl);

var oriVal = inputCtrl.value;

if (keynum == pointCharCode)

{

return oriVal.indexOf(".") == -1;

}

if (keynum == minusCharCode)

{

if (oriVal.indexOf("-") > -1)

return false;

return  index == 0

}

keychar = String.fromCharCode(keynum)

var newVal = oriVal.substr(0, index) + keychar + oriVal.substr(index, oriVal.length - index);

console.log(newVal)

var pattern = /^([-]){0,1}([0-9]){1,}([.]){0,1}([0-9]){0,}$/;

return pattern.test(newVal);

}

</script>

调用方法:

<div id="wrap">         数值:<input id="mc" onkeydown="return onlyNumbers(window.event)"/>

</div>

上一篇:高德地图 室内地图 API 的一些坑


下一篇:【Derby 系列】Apache Derby 功能特点