大家早上好,我有以下函数,可以验证文本输入中只能输入数字字符。问题是,如果我按 Dead 键两次,文本输入中会输入“´”。
input_numeric.onkeydown = numericKeyboard;
function numericKeyboard(e) {
if (e.key != 0 && e.key != 1 && e.key != 2 && e.key != 3 && e.key != 4 && e.key != 5 && e.key != 6 && e.key != 7 && e.key != 8 && e.key != 9) {
e.preventDefault();
}
}
请有人能帮我解决我的问题。
不是阻止默认,而是不允许任何不允许的输入
使用输入事件将处理输入和粘贴
const input_numeric = document.getElementById("numeric");
const notallowed = /[^0-9\.\-\+]/g // add e if you need exponent
const allow = (e) => {
const tgt = e.target;
const text = tgt.value;
tgt.value = text.replace(notallowed,"");
};
input_numeric.addEventListener("input", allow);
<input type="text" id="numeric" />
or just
<input type="number" /> which however will allow .e for example due to numbers like 2.04e10
如果你坚持要preventDefault,我们可以试试这个。请注意,输入事件不能使用 PreventDefault,因为它在输入后触发
const checkInput = (e,pasting) => {
let text;
if (pasting) {
const clipboardData = e.clipboardData || window.clipboardData;
text = clipboardData.getData('Text');
}
else text = e.key;
if (/[^0-9]/.test(text)) {
console.log(`${pasting ? 'Pasting' : 'Input'} is prevented because it contains a non-numeric character.`);
e.preventDefault();
}
};
const field = document.getElementById('numeric');
field.addEventListener('paste', (e) => checkInput(e,true));
field.addEventListener('keydown', (e) => {
checkInput(e, false);
});
<input type="text" id="numeric" />