我有一个由文本框的 onkeydown
事件触发的函数。如何判断用户是否按下了退格键或删除键?
试试这个:
document.addEventListener("keydown", KeyCheck); //or however you are calling your method
function KeyCheck(event)
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 8:
alert("backspace");
break;
case 46:
alert("delete");
break;
default:
break;
}
}
更加简洁明了的方法:使用event.key
。不再需要任意数字编码!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
event.preventDefault();
而不是return false
,因为你的示例不是内联的... - Brett Zamir.key
或.code
属性来处理KeyboardEvent
。从2023年7月起,这些属性在超过97%的用户浏览器中都得到支持。使用它们的代码应该类似于以下内容:document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
.keyCode
属性(尽管请参阅下面关于为何这种旧接口不如新接口的讨论)。document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
}
});
不确定它在 Firefox 以外的浏览器中是否可用:
callback (event){
if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
// do something
}
}
event.DOM_VK_BACK_SPACE
替换为8
,将event.DOM_VK_DELETE
替换为46
或将它们定义为常量(以提高可读性)。