[英]eventListener keypress does not work correcly for the <input>
I understand that using an keypress eventlistener
for the keystrokes in an element of the input
is pure madness. 我知道在
input
元素中使用击键事件keypress eventlistener
进行击键纯属疯狂。 But I personally want to understand for myself what is I'm doing wrong in this case. 但是我个人想自己了解在这种情况下我做错了什么。
The objective of the code - is to allow only numbers to be displayed in the field input
, prohibiting the appearance of letters, as well as the use of keyboard combinations (alt, shift, etc). 代码的目的是 -仅允许在字段
input
显示数字,禁止出现字母,以及使用键盘组合(alt,shift等)。
function onDown(e) { e = e || event; if (e.ctrlKey || e.altKey || e.metaKey) return; // false for key cominations var chr = getChar(e); if (chr == null) return; if (chr < '0' || chr > '9') { // if "chr" do not a digit - false return false; } } function getChar(event) { // support func to get the char from keyCode if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; } inp.addEventListener( 'keypress', onDown );
<input type="text" id="inp">
You need to call e.preventDefault();
您需要调用
e.preventDefault();
when the entered value is not a number. 输入的值不是数字时。
function onDown(e) { e = e || event; if (e.ctrlKey || e.altKey || e.metaKey) return; // false for key cominations var chr = getChar(e); if (chr == null) return; if (chr < '0' || chr > '9') { // if "chr" do not a digit - false e.preventDefault(); } } function getChar(event) { // support func to get the char from keyCode if (event.which == null) { if (event.keyCode < 32) return null; return String.fromCharCode(event.keyCode) } if (event.which != 0 && event.charCode != 0) { if (event.which < 32) return null; return String.fromCharCode(event.which); } return null; } inp.addEventListener('keypress', onDown);
<input type="text" id="inp">
You don't need the getChar
method because event already has key
property. 您不需要
getChar
方法,因为事件已经具有key
属性。
function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function onDown(e) { e = e || event; if (e.ctrlKey || e.altKey || e.metaKey || e.shift) return; // false for key cominations if(!isNumeric(e.key)) e.preventDefault(); } inp.addEventListener( 'keypress', onDown );
<input type="text" id="inp">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.