how to bind key combination ctrl+x+return in jquery

后端 未结 5 658
闹比i
闹比i 2021-01-02 16:59

Is there any way to catch key combination ctrl+x+return in jquery(or javascript), such that if user presses this key combination, a function

5条回答
  •  Happy的楠姐
    2021-01-02 17:41

    Use a global boolean array var keys = [] to check whether a key is pressed. Then use the following function to add a global hotkey:

    window.addGlobalHotkey = function(callback,keyValues){
        if(typeof keyValues === "number")
            keyValues = [keyValues];
    
        var fnc = function(cb,val){
            return function(e){
                keys[e.keyCode] = true;
                executeHotkeyTest(cb,val);
            };        
        }(callback,keyValues);
        window.addEventListener('keydown',fnc);
        return fnc;
    };
    

    As you can see it adds a new listener to the 'keydown' event. This listener will first set the corresponding value in keys true and then execute a test, whether the given keyValues are currently true. Note that you cannot remove keys[e.keyCode] = true and put it in another listener because this could result in a wrong callback order (first hotkey testing, then key mapping). The executeHotkeyTest itself is very easy too:

    window.executeHotkeyTest = function(callback,keyValues){
        var allKeysValid = true;
    
        for(var i = 0; i < keyValues.length; ++i)
            allKeysValid = allKeysValid && keys[keyValues[i]];
    
        if(allKeysValid)
            callback();
    };
    

    At last you have to add another listener to keyup to clean the released keys from keys.

    window.addEventListener('keyup',function(e){
        keys[e.keyCode] = false;
    });
    

    Now you can add a hotkey to ctrl+x+enter by using addGlobalHotkey(callback,[13,17,88]):

    addGlobalHotkey(function(){
        document.body.appendChild(
            document.createElement('div').appendChild(
                document.createTextNode('Ctrl + x + Enter down')
        ).parentNode);
    },[88,13,17]);
    

    JSFiddle demo

    Instead of adding a listener for every hotkey you can use a global [[callback1,values1],[callback2,values2],...] array.

    Important note: in IE prior version 9 you have to use attachEvent instead of addEventListener. Since you're already using jQuery you could use .on(...) or .keydown instead.

提交回复
热议问题