简体   繁体   中英

Combination Keydown function not working for Mac Keyboard

I'm trying to show the Searchbar on my application using keyboard shortcuts.

While the keyboard shortcuts work perfectly using a Windows keyboard, the code fails when I'm using a Mac machine with a Mac keyboard.

Following is the function which I've written -

var osName = "Unknown OS";
if (navigator.appVersion.indexOf("Win") != -1) osName = "Windows";
if (navigator.appVersion.indexOf("Mac") != -1) osName = "MacOS";

function showSearchBarOnKeyPress() {
        $(document).keydown(function (e) {
            if ((e.ctrlKey && e.altKey && e.key === "z") || (osName === "MacOS" && e.keyCode === 90 && e.keyCode === 17 && e.keyCode === 91)) {
                searchBarIsShown();
            }
        });
    }

Initially I didn't have the '||' condition in the 'If' statement. The first condition works when using a Windows keyboard. When I checked on a Mac it didn't work. So I had to put in the '||' condition.

For the MacOS condition initially I had used keycodes - 59,55 and 6 as shown in this reference - https://eastmanreference.com/complete-list-of-applescript-key-codes

On checking in the Mac machine, the keycodes detected were - 90,91 and 17 which I then replaced.

But it still doesn't work.

Can someone please provide their insights/thoughts on this issue?

Thanks

e.ctrlKey and e.altKey are special properties on the KeyboardEvent object that contain the state of these buttons.

e.keyCode === 90 && e.keyCode === 17 && e.keyCode === 91

the property e.keyCode can not be three differrent values at once.


I have little experience with apple but I assume you'd have to manually keep track of the state of these buttons.

a simple statemanager would be:

keyDown[90] && keyDown[17] && keyDown[91]

so now you can check all three Buttons at once:

 keyDown[90] && keyDown[17] && keyDown[91] 

try this: metaKey is cmd key on mac. altKey is the option key on mac.

var osName = "Unknown OS";
if (navigator.appVersion.indexOf("Win") != -1) osName = "Windows";
if (navigator.appVersion.indexOf("Mac") != -1) osName = "MacOS";

function showSearchBarOnKeyPress() {
    $(document).keydown(function (e) {
    var modifier = (navigator.appVersion.indexOf("Mac") != -1) ? e.ctrlKey : e.metaKey;
        if (modifier && e.altKey && e.key === "z") {
            searchBarIsShown();
        }
    });
}

note that metaKey is not supported on old browseres..

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