SoFunction
Updated on 2025-03-02

Examples and usage of js simple encapsulation monitoring shortcut key object

js simply encapsulate an object that listens to shortcut keys

export default class Shortcuts {
    keyCodeMap = new Map([
        ["0", 48],
        ["1", 49],
        ["2", 50],
        ["3", 51],
        ["4", 52],
        ["5", 53],
        ["6", 54],
        ["7", 55],
        ["8", 56],
        ["9", 57],
        ["A", 65],
        ["B", 66],
        ["C", 67],
        ["D", 68],
        ["E", 69],
        ["F", 70],
        ["G", 71],
        ["H", 72],
        ["I", 73],
        ["J", 74],
        ["K", 75],
        ["L", 76],
        ["M", 77],
        ["N", 78],
        ["O", 79],
        ["P", 80],
        ["Q", 81],
        ["R", 82],
        ["S", 83],
        ["T", 84],
        ["U", 85],
        ["V", 86],
        ["W", 87],
        ["X", 88],
        ["Y", 89],
        ["UP", 38],
        ["RIGHT", 39],
        ["DOWN", 40],
        ["LEFT", 37],
        ["CTRL", 17],
        ["SHIFT", 16],
        ["ALT", 18],
        ["SPACE", 32],  // Spacebar    ]);
    constructor(keyNames = [], callback, isPreventDefault = false) {
        ();
         = isPreventDefault;
         = keyNames;
         = callback;
        ()
    }
    initEventListener() {
        ("keyup", (this))
    }
    destroy() {
        ("keyup", (this))
    }
    handleKeyup(e) {
         && ();  // Whether to block default behavior        let conditions = []
        if (()) {  // Arrays are key combinations            (code => {
                let strCode = ().toUpperCase();
                switch (strCode) {
                    case "CTRL":
                        ()
                        break;
                    case "SHIFT":
                        ()
                        break;
                    case "ALT":
                        ()
                        break;
                    default:
                        ((strCode) == )
                        break;
                }
            })
        }else {
            let strCode = ().toUpperCase();
            if(strCode == ){
                (true); 
            }
        }
        if ((item => item)) {
             && ()
        }
    }
}

use

    new Shortcuts(["ctrl", "q"], ()=>{  //Key combination      (111);
    });
    new Shortcuts("q", ()=>{  // Single key      (111);
    });

The above is the example and detailed content of JS's simple encapsulated monitoring shortcut key object. For more information about JS's encapsulated monitoring shortcut key object, please pay attention to my other related articles!