简体   繁体   English

如何判断插入键是否被按下

[英]How to tell if insert key has been held down

I'm trying to capture certain keydown events in my application but only if no "control" keys have been held down at the same time. 我试图在我的应用程序中捕获某些keydown事件,但前提是同时没有按下“控制”键。 I don't want to run into issues with screen reader keyboard shortcuts. 我不想遇到屏幕阅读器键盘快捷方式的问题。 Shift , Ctrl and Alt are easy to check for because they're on the javascript event, but I also need to check for Ins and Windows keys as well as any Mac control keys. ShiftCtrlAlt很容易检查,因为它们是在javascript事件上,但我还需要检查InsWindows键以及任何Mac控制键。

This is what I've got so far and it works as expected, but my event is still triggered when Ins or Windows is held down. 这是我到目前为止所做的并且它按预期工作,但是当InsWindows被按下时我的事件仍然被触发。

handleKeydown: function(event) {
  var comboKeyPressed = event.ctrlKey || event.shiftKey || event.altKey;
  if(!comboKeyPressed && event.keyCode === $.ui.keyCode.HOME) {
    event.preventDefault();
    this.$('>ul>li:last').attr('tabindex', -1);
    this.$('>ul>li:first').attr('tabindex', 0).focus();
  } else if (!comboKeyPressed && event.keyCode === $.ui.keyCode.END) {
    event.preventDefault();
    this.$('>ul>li:first').attr('tabindex', -1);
    this.$('>ul>li:last').attr('tabindex', 0).focus();

  }
}

Is there a way to check for other control keys easily or do I need to capture those events and hold onto them in some global Boolean like this.isInsertPressed ? 有没有办法轻松检查其他控制键,还是我需要捕获这些事件并在某些全局布尔值中保留它们,如this.isInsertPressed

You could do something like this: 你可以这样做:

var keysPressed = {};
var keys = { insert: 45 };    
$(window).keydown(function(e) { keysPressed[e.which] = true; });
$(window).keyup(function(e) { keysPressed[e.which] = false; });

And then later: 然后是:

if (keysPressed[keys.insert]) {
    // insert key is currently down
}

Event object使用keycode属性

if(event.keyCode === 45) // Insert Key

Use event.key and modern JS! 使用event.key和现代JS!

No number codes anymore. 没有数字代码了。 You can check for Insert key directly. 您可以直接检查插入键。

let isInsertDown = false;
document.addEventListener("keydown", function (event) {
    if (event.key === "Insert") {
        isInsertDown = true;
    }
});
document.addEventListener("keyup", function (event) {
    if (event.key === "Insert") {
        isInsertDown = false;
    }
});

Mozilla Docs Mozilla文档

Supported Browsers 支持的浏览器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM