[英]Keydown Events are not working in Javascript
为了好玩,我正在尝试使用基本的计算器。 我尝试附加一些事件,以便用户 van 使用 ENTER 获取结果并使用退格键返回。 但是,键盘事件不起作用。
我也不明白为什么在按下以清空屏幕框时 C 会出现在屏幕框中。
可能是什么问题??
我做了一个小提琴: https : //jsfiddle.net/9gvbd2nt/1/
const screen = document.getElementById('screen');
let screenValue = '';
const allowed = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', '=', '-', '/', '*', '+', ')', 'C'];
document.querySelectorAll('button').forEach((b) => {
b.addEventListener('click', (e) => {
let button = e.target.innerText;
if (screenValue == '' && allowed.splice(11, 15).includes(button)) {
console.log('Invalid Character: ' + button)
}
if (button === 'C') {
screenValue = '';
screen.value = screenValue;
}
if (button === '=') {
evalTest(screen.value);
} else {
screenValue += button;
screen.value = screenValue;
}
screen.focus();
})
})
document.addEventListener("keydown", (e) => {
if (e.key === 13) {
e.preventDefault;
evalTest(screen.value);
}
if (e.key === 8) {
e.preventDefault;
screenValue = screenValue.slice(-1);
screen.value = screenValue;
}
})
function evalTest(value) {
const regex = new RegExp('[0-9\/\*\)\(\+\-\=\%]*')
if (value.match(regex)[0] == value) {
screen.value = eval(value);
} else {
alert('Illegal Operation');
}
}
将e.key
更改为e.which
或e.keyCode
。
document.addEventListener("keydown", (e) => {
if (e.which === 13) {
e.preventDefault;
evalTest(screen.value);
}
if (e.which === 8) {
e.preventDefault;
screenValue = screenValue.slice(-1);
screen.value = screenValue;
}
})
更新:不推荐使用which
和keyCode
属性。 您不应该使用 ASCII 值来检查key
属性,而应该使用key
的名称:
document.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault;
evalTest(screen.value);
}
if (e.key === "Backspace") {
e.preventDefault;
screenValue = screenValue.slice(-1);
screen.value = screenValue;
}
})
如果您想在将来检查其他人,这里有一个关键值列表:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.