Robust keyboard shortcut handling using JavaScript

前端 未结 5 362
轮回少年
轮回少年 2020-12-17 04:07

What\'s the most robust way of creating a global keyboard shortcut handler for a Web application using JavaScript i.e. which event(s) should I handle and what should the eve

相关标签:
5条回答
  • 2020-12-17 04:14

    What I would do is attach onKeyUp events to the document.body. Then, in this event handler, I would use the Element.fire method to fire a custom event. Though this step is optional, it will help in decoupling the event handler from the action to be performed, and you can use the same custom-event handler from say an button click event.

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

    Later, to bind the same event to a button click:

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

    As far as handling modifier keys is concerned, check out this resource (very old, but still looks applicable) for more help.

    0 讨论(0)
  • 2020-12-17 04:16

    There is also new JavaScript library called jwerty, it's easy to use and doesn't rely on jQuery.

    0 讨论(0)
  • 2020-12-17 04:23

    The HotKey library available in the LivePipe controls package works with Prototype and is IE compatible.

    http://livepipe.net/extra/hotkey

    0 讨论(0)
  • 2020-12-17 04:24

    JimmyP posted this as a comment, but it deserves to be an answer for voting purposes.

    http://www.openjs.com/scripts/events/keyboard_shortcuts/

    0 讨论(0)
  • 2020-12-17 04:32

    Just thought I'd throw another into the mix. I recently released a library called Mousetrap. Check it out at http://craig.is/killing/mice

    0 讨论(0)
提交回复
热议问题