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

时间:2013-08-01 22:03:27

标签: javascript jquery events keydown

我正在尝试捕获应用程序中的某些keydown事件,但前提是同时没有按下“控制”键。我不想遇到屏幕阅读器键盘快捷方式的问题。 ShiftCtrlAlt很容易检查,因为它们出现在javascript事件中,但我还需要检查InsWindows个键以及任何Mac控制键。

这是我到目前为止所做的并且它按预期工作,但在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();

  }
}

有没有办法轻松检查其他控制键,还是我需要捕获这些事件并在某些全局布尔值中保留它们,如this.isInsertPressed

3 个答案:

答案 0 :(得分:3)

你可以这样做:

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

然后是:

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

答案 1 :(得分:1)

Event object

中使用键码属性
if(event.keyCode === 45) // Insert Key

答案 2 :(得分:0)

使用 //notice, no caps on Int, otherwise you'd need Int32 as the declaration int n = GetSomeValueSoNEqualsSomething(); //String and string are both correct, but try to use the lowercase for variables, // uppercase for class methods. string numbers = "1,2,3"; //split the string into an array of strings delimiting by comma string[] nums = numbers.Split(','); //now, you can either check against the string return nums.Contains(n.ToString()); //string compare to return a bool //or check via a loop and parse the numbers foreach (var s in nums) { if(int.Parse(s) == n) return true; } //int compare to return a bool 和现代JS!

没有数字代码了。您可以直接检查 Insert 键。

event.key

Mozilla Docs

Supported Browsers