Hotkeys-js

一个没有其他依赖的,能够捕获键盘输入和输入组合键的库。

在日常业务中,监听键盘事件是最为平常不过的事情,而 hotkeys-js 不仅轻量,还容易使用,所以在这里简单记录一下其用法。在 vue 中,比较推荐使用 vue-global-events,后面会提及。

一般用法

引入打包好的js:

<script type="text/javascript" src="hotkeys.js"></script>

或者打包到项目中:

npm install hotkeys-js

import hotkeys from 'hotkeys-js'

然后,就可以进行简单的绑定操作:

// 监听 shift+a 组合键
hotkeys('shift+a', function (e) {
    console.log('操作了 shift+a: ', e)
})

当然,以上操作都是作用在全局范围的。当你在单页面应用中,不同页面对相同快捷键做不同的处理时,可以通过解除绑定然后再重新绑定的方式实现。

hotkeys.unbind('shift+a')
hotkeys.unbind('shift+a', 'scope')

但是这样操作有点繁琐,借助区域范围的话会方便很多。

// 标记在 scope 的监听事件
hotkeys('shift+a', 'scope', () => {
    console.log('scope')
})
// 标记在 scope1 的监听事件
hotkeys('shift+a', 'scope1', () => {
    console.log('scope1')
})
// 通过 setScope 设定范围 scope
hotkeys.setScope('scope')
// 删除已设定的范围
hotkeys.deleteScope('scope')

hotkeys api

// 键盘对应值
var key = 'shift' || 'ctrl' || ...
// 返回是否被按 返回 boolean
hotkeys[key]
// 与上面功能相同 返回 boolean
hotkeys.isPressed(key) == hotkeys[key]
// 获取摁下绑定键的键值
hotkeys.getPressedKeyCodes()

// filter 过滤处理
hotkeys.filter = (e) => ture
// 如过滤掉 INPUT、SELECT、TEXTAREA 不处理 & 可编辑标签 <div contentEditable="true"></div>
hotkeys.filter = (e) => {
    let tagName = (e.target || e.srcElement).tagName.toUpperCase()
    return !(tagName.isContenEditable ||
            tagName == 'INPUT' ||
            tagName == 'SELECT' ||
            tagname == 'TEXTAREA')
}

兼容模式

if (typeof window !== 'undefined') {
    var _hotkeys = window.hotkeys;
    hotkeys.noConflict = (deep) => {
        if (deep && window.hotkeys === hotkeys) {
            window.hotkeys = _hotkeys
        }
        return hotkeys
    }
    window.hotkeys = hotkeys
}

为了避免 windowhotkeys 属性冲突或被覆盖。

封装

适当对 hotkeys 进行封装,可以更加方便调用。

  1. 在 bind 时,把当前范围已注册的 key 记录下拉,避免重复注册;
  2. unbind 并同时删除注册记录;
  3. 记录当前区域范围,在设置区域范围马上更改;
let scope = 'global'
const _regKeys = []
export.curScope = scope
function bind(keys: string | string[], cb: (e, handler) => any, scope = 'global') {
    ...
    let key = scope + ':' + keys
    if (_regKeys.indexOf(key) > -1) {
        console.log(key + '已经注册使用')
        return false
    }
    _regKeys.push(key)
    ...
}

function set(scope: string) {
    hotkeys.setScope(scope)
    export.curScope = scope
}

results matching ""

    No results matching ""