Javascript 如何在 onkeydown 事件中捕获退格键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2353550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:54:11  来源:igfitidea点击:

How to capture a backspace on the onkeydown event

javascriptonkeydown

提问by Raphael

I have a function that is triggered by the onkeydownevent of a textbox. How can I tell if the user has hit either the backspace key or the del key?

我有一个由onkeydown文本框事件触发的函数。如何判断用户是否按下了退格键或 del 键?

回答by Stephano

Try this:

尝试这个:

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;
   }
}

回答by Mark Amery

Nowadays, code to do this should look something like:

如今,执行此操作的代码应如下所示:

document.getElementById('foo').addEventListener('keydown', function (event) {
    if (event.keyCode == 8) {
        console.log('BACKSPACE was pressed');

        // Call event.preventDefault() to stop the character before the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
    if (event.keyCode == 46) {
        console.log('DELETE was pressed');

        // Call event.preventDefault() to stop the character after the cursor
        // from being deleted. Remove this line if you don't want to do that.
        event.preventDefault();
    }
});

although in the future, once they are broadly supported in browsers, you may want to use the .keyor .codeattributes of the KeyboardEventinstead of the deprecated .keyCode.

尽管在未来,一旦它们在浏览器中得到广泛支持,您可能希望使用 的.key.code属性KeyboardEvent而不是已弃用的.keyCode.

Details worth knowing:

值得了解的细节:

  • Calling event.preventDefault()in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to documentinstead of a text field).

  • Documentation on how the value of the keyCodeattribute is determined can be found in section B.2.1 How to determine keyCodefor keydownand keyupeventsin the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.

  • There is an effort underway to deprecate the .keyCodeattribute in favour of .keyand .code. The W3 describe the .keyCodeproperty as "legacy", and MDN as "deprecated".

    One benefit of the change to .keyand .codeis having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace"and "Delete"and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypressand the physical key that was pressed.

    On small Mac keyboards, there is no Deletekey, only a Backspacekey. However, pressing Fn+Backspaceis equivalent to pressing Deleteon a normal keyboard - that is, it deletes the character afterthe text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspacewith Fnheld down as either Backspace or Delete. That's why the new key model lets you choose.

    The .keyattribute gives you the meaningof the keypress, so Fn+Backspacewill yield the string "Delete". The .codeattribute gives you the physical key, so Fn+Backspacewill still yield the string "Backspace".

    Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCodeattribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:

    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');
        }
    });
    
  • 调用event.preventDefault()keydown 事件的处理程序将阻止按键的默认效果。当按下一个字符时,这会阻止它被输入到活动文本字段中。在文本字段中按退格键或删除键时,可防止删除字符。在没有活动文本字段的情况下按退格键时,在像 Chrome 这样的浏览器中,退格键会将您带回上一页,它会阻止这种行为(只要您通过添加事件侦听器document而不是文本字段来捕获事件)。

  • 关于如何keyCode确定属性值的文档可以在 W3 的 UI 事件规范中的B.2.1 如何确定keyCodeforkeydownkeyup事件中找到。特别是 Backspace 和 Delete 的代码在B.2.3 固定虚拟键代码中列出。

  • 正在努力弃用该.keyCode属性以支持.key.code。W3 将该.keyCode属性描述为"legacy",MDN 描述为"deprecated"

    更改.key和 的一个好处.code是对非 ASCII 键进行更强大和对程序员友好的处理 - 请参阅列出所有可能键值的规范,这些键值是人类可读的字符串,例如"Backspace""Delete",包括从特定修饰键开始的所有内容的值到日语键盘以隐藏媒体键。另一个与此问题高度相关的问题是区分修改后的按键按下的物理按键的含义

    小型 Mac 键盘上,没有Delete键,只有一个Backspace键。但是,按Fn+Backspace相当于Delete在普通键盘上按- 也就是说,它会删除文本光标之后的字符而不是它之前的字符。根据您的用例,在代码中,您可能希望将按住 的Backspace和处理Fn为退格键或删除键。这就是为什么新的密钥模型让您选择的原因。

    .key属性为您提供了按键的含义,因此Fn+Backspace将产生字符串"Delete"。该.code属性为您提供物理键,因此Fn+Backspace仍会产生字符串"Backspace"

    不幸的是,在撰写此答案时,它们仅在 18% 的浏览器中受支持,因此如果您需要广泛的兼容性.keyCode,则暂时只能使用“legacy”属性。但是,如果您是未来的读者,或者您的目标是特定平台并且知道它支持新界面,那么您可以编写如下所示的代码:

    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');
        }
    });
    

回答by Gibolt

event.key === "Backspace" or "Delete"

event.key === "退格" 或 "删除"

More recent and much cleaner: use event.key. No more arbitrary number codes!

更新更干净:使用event.key. 没有更多的任意数字代码!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Mozilla 文档

Supported Browsers

支持的浏览器

回答by jasonbar

In your function check for the keycode 8 (backspace) or 46 (delete)

在您的函数中检查键码 8(退格)或 46(删除)

Keycode information
Keycode list

键码信息
键码列表

回答by Mathieu

not sure if it works outside of firefox:

不确定它是否在 Firefox 之外工作:

callback (event){
  if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
    // do something
  }
}

if not, replace event.DOM_VK_BACK_SPACEwith 8and event.DOM_VK_DELETEwith 46or define them as constant (for better readability)

如果没有,请更换event.DOM_VK_BACK_SPACE8event.DOM_VK_DELETE46或将它们定义为常数(更好的可读性)