我正在尝试为一个基本的计算器工作。我尝试附加一些事件,以便用户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
属性,而只能使用键名:
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/zh-CN/docs/Web/API/KeyboardEvent/key/Key_Values
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句