我有以下代码:
function noNumbers(e)
{
var charCode = (e.which) ? e.which :
((e.charCode) ? e.charCode :
((e.keyCode) ? e.keyCode : 0));
if((charCode < 48 || charCode > 57) && (charCode > 45 || charCode < 47))
e.preventDefault();
}
目标是让用户可以输入数字、退格键和删除键。它适用于 Chrome 和 IE,但在 Firefox 中,您只能键入数字,而不能键入退格键或删除键。
JS小提琴:https://jsfiddle.net/sdy9gd0g/
为什么不处理input事件代替?此方法将通过键盘输入、剪切、粘贴等处理实时更改。
(function() {
var textBox = document.getElementById("text-box");
textBox.addEventListener("input", function(e) {
var val = this.value,
rx = /[^\d]/g;
if (rx.test(val)) {
var pos = this.selectionStart;
this.value = val.replace(rx, "");
this.selectionStart = pos;
this.selectionEnd = pos - 1;
}
});
})();
<input id="text-box" autofocus>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)