简体   繁体   中英

Preferred way of responding to a keyboard shortcut in JavaScript

The Inte.net is full of ideas on this one, but many of them are dated, and many of them are platform specific.

If I want to respond to a keyboard shortcut for save ( ⌘S on Mac, control-S on Linux/Windows), I know I can try something like this:

document.onkeypress=doit;
function doit(event) {
    if(event.metaKey||event.ctrlKey) {
        switch(event.key) {
            case s: doSomething();
                break;
            //  etc
        }
    }
}

The problem is the metaKey should only work on Mac, while ctrlKey should only work on Linux/Windows. Also, I can't find a simple answer to whether I should use the keypress event or keyup or keydown .

The question is, what is the preferred way of doing this?

OK, here is a solution.

Using that, I can use something like:

document.addEventListener('keydown',doit);
function doit(event) {
    if(event.metaKey || event.ctrlKey) {
        switch(event.key) {
            case s:
                doSomething();
                event.preventDefault();     //  Don’t Save
                break;
            //  etc
        }
    }
}

This doesn't distinguish when a Mac user presses ctrl-s , but any Mac user who does that should expect a surprise.

You might find Keystrokes helpful. It has no dependencies and is very easy to use.

Using it, your code would look like this:

import { bindKeyCombo } from '@rwh/keystrokes'

bindKeyCombo('super > s', doSomething)
bindKeyCombo('ctrl > s', doSomething)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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