JS頁面快捷鍵庫hotkeys.js

網友提供了一個好用的快捷鍵庫,沒有任何依賴,這是一個強健的 Javascript 庫用於捕獲鍵盤輸入和輸入的組合鍵,它沒有依賴,壓縮只有只有(~3kb)。javascript

這裏也要特別感謝園友kacper的提醒與提供參考。html

下面我把源碼貼出來,僅供本身和你們學習參考。java

下面給出hotkeys.js文件內容:api

//IE對indexOf方法的支持
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){              
        for(var i=0; i<this.length; i++) if(this[i]===obj) return i;
        return -1;
    };
}

;(function(root, factory) {
    var hotkeys = factory(root);
    if (typeof define === 'function' && define.amd) {
        // AMD
        define('hotkeys', function() { return hotkeys; });
    } else if (typeof exports === 'object') {
        // Node.js
        module.exports = hotkeys;
    } else {
        // Browser globals
        // previousKey存儲先前定義的關鍵字
        var previousKey = root.hotkeys;
        hotkeys.noConflict = function() {
            var k = root.hotkeys;
            root.hotkeys = previousKey;
            return k;
        };
        root.hotkeys = hotkeys;
    }
}(this, function(root, undefined) {
    var _api,//對外API
    _keyMap = {//特殊鍵
        backspace: 8, tab: 9, clear: 12,
        enter: 13, 'return': 13,
        esc: 27, escape: 27, space: 32,
        left: 37, up: 38, right: 39, down: 40,
        del: 46, 'delete': 46,
        home: 36, end: 35,
        pageup: 33, pagedown: 34,
        ',': 188, '.': 190, '/': 191,
        '`': 192, '-': 189, '=': 187,
        ';': 186, '\'': 222,
        '[': 219, ']': 221, '\\': 220
    },
    _scope = 'all',//默認熱鍵範圍
    _modifier = {//修飾鍵
        '⇧': 16, shift: 16,
        '⌥': 18, alt: 18, option: 18,
        '⌃': 17, ctrl: 17, control: 17,
        '⌘': 91, command: 91
    },
    _downKeys=[],//記錄摁下的綁定鍵
    modifierMap = {
        16:'shiftKey',
        18:'altKey',
        17:'ctrlKey',
        91:'metaKey'
    },
    _mods = { 16: false, 18: false, 17: false, 91: false },
    //返回鍵碼
    code = function(x){ 
        console.log();
      return _keyMap[x] || x.toUpperCase().charCodeAt(0);
    },
    _handlers={};
    // F1~F12 特殊鍵
    for(k=1;k<20;k++) {
        _keyMap['f'+k] = 111+k;
    }

    //設置獲取當前範圍(默認爲'全部')
    function setScope(scope){ _scope = scope || 'all';}
    function getScope(){ return _scope || 'all';}
    //綁定事件
    function addEvent(object, event, method) {
        if (object.addEventListener){
            object.addEventListener(event, method, false);
        }else if(object.attachEvent){
            object.attachEvent('on'+event, function(){ method(window.event); });
        }
    }
    //判斷摁下的鍵是否爲某個鍵,返回true或者false
    function isPressed(keyCode) {
        if(typeof(keyCode) === 'string'){
            keyCode = code(keyCode);//轉換成鍵碼
        }
        return _downKeys.indexOf(keyCode) !==-1;
    }
    //獲取摁下綁定鍵的鍵值
    function getPressedKeyCodes (argument) { return _downKeys.slice(0);}
    //處理keydown事件
    function dispatch (event) {
        var key = event.keyCode,scope,asterisk = _handlers['*'];

        //蒐集綁定的鍵
        if(_downKeys.indexOf(key)===-1) _downKeys.push(key);
        //Gecko(Friefox)的command鍵值224,在Webkit(Chrome)中保持一致
        //Webkit左右command鍵值不同
        if(key === 93 || key === 224) key = 91;
        if(key in _mods) {
            _mods[key] = true;
            // 將特殊字符的key註冊到 hotkeys 上
            for(var k in _modifier)if(_modifier[k] === key) hotkeys[k] = true; 
            if(!asterisk) return;
        }
        //將modifierMap裏面的修飾鍵綁定到event中
        for(var e in _mods) _mods[e] = event[modifierMap[e]];

        //表單控件控件過濾 默認表單控件不觸發快捷鍵
        if(!hotkeys.filter.call(this,event)) return;
        //獲取範圍 默認爲all
        scope = getScope();

        //對任何按鍵作處理
        if(asterisk) for (i = 0; i < asterisk.length; i++) {
            if(asterisk[i].scope === scope) eventHandler(event,asterisk[i],scope);
        }

        // key 不在_handlers中返回
        if (!(key in _handlers)) return;

        for (i = 0; i < _handlers[key].length; i++) {
            //找處處理內容
            eventHandler(event,_handlers[key][i],scope);
        }
    }

    function eventHandler(event,handler,scope){
        var modifiersMatch;
        //看它是否在當前範圍
        if(handler.scope === scope || handler.scope === 'all'){
            //檢查是否匹配修飾符(若是有返回true)
            modifiersMatch = handler.mods.length > 0;
            for(var y in _mods){
                if((!_mods[y] && handler.mods.indexOf(+y) > -1) ||
                    (_mods[y] && handler.mods.indexOf(+y) === -1)) modifiersMatch = false;
            }
            // 調用處理程序,若是是修飾鍵不作處理
            if((handler.mods.length === 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch || handler.shortcut === '*'){
                if(handler.method(event, handler)===false){
                    if(event.preventDefault) event.preventDefault();
                    else event.returnValue = false;
                    if(event.stopPropagation) event.stopPropagation();
                    if(event.cancelBubble) event.cancelBubble = true;
                }
            }
        }
    }

    //解除綁定某個範圍的快捷鍵
    function unbind (key,scope) {
        var multipleKeys = getKeys(key),keys,mods = [],obj;
        for (var i = 0; i < multipleKeys.length; i++) {
            
            //將組合快捷鍵拆分爲數組
            keys =multipleKeys[i].split('+');
            
            //記錄每一個組合鍵中的修飾鍵的鍵碼 返回數組
            if(keys.length > 1) mods=getMods(keys);
            
            //獲取除修飾鍵外的鍵值key
            key = keys[keys.length - 1];
            key = code(key);

            //判斷是否傳入範圍,沒有就獲取範圍
            if(scope === undefined) scope = getScope();

            //如何key不在 _handlers 中返回不作處理
            if (!_handlers[key]) return;

            //清空 handlers 中數據,
            //讓觸發快捷鍵鍵以後沒有事件執行到達解除快捷鍵綁定的目的
            for (var r = 0; r < _handlers[key].length; r++) {
                obj = _handlers[key][r];
                //判斷是否在範圍內而且鍵值相同
                if (obj.scope === scope && compareArray(obj.mods, mods)) {
                  _handlers[key][r] = {};
                }
            }
        }
    }
    //循環刪除handlers中的全部 scope(範圍)
    function deleteScope(scope){
        var key, handlers, i;
        for (key in _handlers) {
            handlers = _handlers[key];
            for (i = 0; i < handlers.length; ) {
                if (handlers[i].scope === scope) handlers.splice(i, 1);
                else i++;
            }
        }
    }
    //比較修飾鍵的數組
    function compareArray(a1, a2) {
        if (a1.length !== a2.length) return false;
        for (var i = 0; i < a1.length; i++) {
            if (a1[i] !== a2[i]) return false;
        }
        return true;
    }
    //表單控件控件判斷 返回 Boolean
    function filter(event){
        var tagName = (event.target || event.srcElement).tagName;
        //忽略這些標籤狀況下快捷鍵無效
        return !(tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA');
    }
    //修飾鍵轉換成對應的鍵碼
    function getMods (key) {
        var mods = key.slice(0, key.length - 1);
        for (var i = 0; i < mods.length; i++) mods[i] = _modifier[mods[i]];
        return mods;
    }
    //處理傳的key字符串轉換成數組
    function getKeys(key) {
        var keys;
        key = key.replace(/\s/g, '');//匹配任何空白字符,包括空格、製表符、換頁符等等
        keys = key.split(',');
        if ((keys[keys.length - 1]) === '') keys[keys.length - 2] += ',';
        return keys;
    }

    //在全局document上設置快捷鍵
    addEvent(document, 'keydown', function(event) {
        dispatch(event);
    });
    addEvent(document, 'keyup',function(event){
        clearModifier(event);
    });
    //清除修飾鍵
    function clearModifier(event){
        var key = event.keyCode,
            i = _downKeys.indexOf(key);

        if(i>=0) _downKeys.splice(i,1);

        //修飾鍵 shiftKey altKey ctrlKey (command||metaKey) 清除
        if(key === 93 || key === 224) key = 91;
        if(key in _mods) {
            _mods[key] = false;
            for(var k in _modifier) if(_modifier[k] === key) hotkeys[k] = false;
        }
    }
    //主體hotkeys函數
    function hotkeys(key,scope,method){
        var keys = getKeys(key), mods=[],i=0;
        //對爲設定範圍的判斷
        if (method === undefined) {
            method = scope;
            scope = 'all';
        }
        //對於每一個快捷鍵處理
        for(;i < keys.length; i++){
            key = keys[i].split('+');
            mods = [];
            //若是是組合快捷鍵取得組合快捷鍵
            if (key.length > 1){
                mods = getMods(key);
                key = [key[key.length-1]];
            }
            //轉換成鍵碼
            key = key[0];
            key = key === '*' ? '*' : code(key);
            //判斷key是否在_handlers中,不在就賦一個空數組
            if (!(key in _handlers)) _handlers[key] = [];
            _handlers[key].push({shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods});
        }
    }
    _api = {
        setScope:setScope,
        getScope:getScope,
        deleteScope:deleteScope,
        getPressedKeyCodes:getPressedKeyCodes,
        isPressed:isPressed,
        filter:filter,
        unbind:unbind
    };
    for (var a in _api) hotkeys[a] = _api[a];
    return hotkeys;
}));

而後就能夠在您的HTML頁面上進行引用了,以下的test.html頁面:數組

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hotkeys</title>
    <script type="text/javascript" src="../src/hotkeys.js"></script>
</head>
<body>
    <div style="height: 60px;width: 600px;border: 1px solid red;">按alt+c鍵會在console中輸出信息,分別把光標定位在body中、div中、textarea中
    而後再按alt+c分別會激發不一樣的開關,可使用alt+o和o兩種鍵組合,分別執行不一樣的功能,本例是都在console中輸出信息。</div>
    <br />
    <textarea></textarea>
    <div id=ddd contentEditable="true" style="height: 100px;width: 400px;border: 1px solid red;"></div>
<script type="text/javascript">

    hotkeys.filter = function(event){
        //console.log("message123123123",event.target);
        return true;
    }
    
   // 定義a快捷鍵
    hotkeys('alt+c',function(event,handler){
        //event.srcElement: input 
        //event.target: input
        console.log("message22323:",event.target);
        
        // 設定範圍scope 
        if(event.target.tagName=="TEXTAREA")
            hotkeys.setScope('issues');
        if(event.target.tagName=="DIV")
            hotkeys.setScope('files');
    });

// 一個快捷鍵,有可能幹的活兒不同哦
hotkeys('alt+o, ctrl+alt+enter', 'issues', function(){
    console.log('乾點活兒');
});
hotkeys('o, enter', 'files', function(){ 
    console.log('另外一種活兒');
});

</script>
</body>
</html>

 以上代碼我已經打包,你能夠下載使用,下載地址:hotkeys-jaywcjlove-4e99489函數

另外,你也能夠到hotkeys的官方網站上下載最新的JS庫代碼以及使用手冊說明,網址:http://jslite.io/hotkeys/學習

版權聲明:版權歸hotkeys官方全部,若有侵權,請告知本人,本人將當即對發帖採起處理。官方網站:http://jslite.io/hotkeys/網站

相關文章
相關標籤/搜索