代码之家  ›  专栏  ›  技术社区  ›  John Topley

使用JavaScript进行强大的键盘快捷键处理

  •  6
  • John Topley  · 技术社区  · 17 年前

    使用JavaScript为Web应用程序创建全局键盘快捷键处理程序的最稳健方法是什么,即我应该处理哪些事件,事件处理程序应该附加到什么?

    我想要像Gmail中的系统一样,既能处理单键快捷键,也能处理带有修饰键的快捷键,例如Ctrl+B等。该代码必须在IE 6和现代浏览器中工作。

    我有Prototype框架可供使用,但没有jQuery,所以请不要给出jQuery特定的答案!

    6 回复  |  直到 14 年前
        1
  •  6
  •   Craig    13 年前
        2
  •  5
  •   james    17 年前
        4
  •  3
  •   Rakesh Pai    17 年前

    我要做的就是将onKeyUp事件附加到document.body中。然后,在这个事件处理程序中,我将使用 Element.fire

    $(document.body).observe("keyup", function() {
        if(/* key + modifier match */) {
            $(document.body).fire("myapp:mycoolevent");
        }
    });
    
    $(document.body).observe("myapp:mycoolevent", function() {
        // Handle event.
    });
    

    $(button).observe("click", function() {
        $(document.body).fire("myapp:mycoolevent");
    });
    

    this resource

        5
  •  2
  •   Keithamus Prashant    11 年前

    jwerty ,它易于使用,不依赖于jQuery。

        6
  •  0
  •   Robert Hurst Patrick Ryan    3 年前

    Keystrokes

    import { bindKey, bindKeyCombo } from '@rwh/keystrokes'
    
    bindKey('a', () =>
      console.log('You\'re pressing "a"'))
    
    bindKeyCombo('ctrl > y, r', () =>
      console.log('You pressed "ctrl" then "y", released both, and are pressing "r"'))