From c48a2d4a23a8b8e95188952f5e0486eb69c5fcc2 Mon Sep 17 00:00:00 2001 From: jaywcjlove <398188662@qq.com> Date: Thu, 21 Mar 2019 14:34:51 +0800 Subject: [PATCH] option add keyup parameter. #57 --- README-zh.md | 15 +++++++++++++++ README.md | 16 ++++++++++++++++ src/main.js | 8 ++++++-- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/README-zh.md b/README-zh.md index 6ca0156..be17d77 100644 --- a/README-zh.md +++ b/README-zh.md @@ -306,6 +306,21 @@ hotkeys('command+ctrl+shift+a,f', function(){ }) ``` +## keyup + +**key down** 和 **key up** 将都执行回调事件。 + +```js +hotkeys('ctrl+a,alt+a+s', { keyup: true }, (evn, handler) => { + if(evn.type === 'keydown') { + console.log('keydown:', evn.type, handler, handler.key); + } + if(evn.type === 'keyup') { + console.log('keyup:', evn.type, handler, handler.key); + } +}); +``` + ## 过滤 `INPUT` `SELECT` `TEXTAREA` 默认不处理。 diff --git a/README.md b/README.md index 958fddd..4d6740b 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,7 @@ hotkeys('*','wcj', function(e){ - `scope` - `element` +- `keyup` ```js hotkeys('o, enter', { @@ -263,6 +264,21 @@ hotkeys('a', function(){ }); ``` +## keyup + +**key down** and **key up** both perform callback events. + +```js +hotkeys('ctrl+a,alt+a+s', { keyup: true }, (evn, handler) => { + if(evn.type === 'keydown') { + console.log('keydown:', evn.type, handler, handler.key); + } + if(evn.type === 'keyup') { + console.log('keyup:', evn.type, handler, handler.key); + } +}); +``` + ### getPressedKeyCodes returns an array of key codes currently pressed. diff --git a/src/main.js b/src/main.js index 485820d..b7e2b3f 100644 --- a/src/main.js +++ b/src/main.js @@ -158,6 +158,7 @@ function eventHandler(event, handler, scope) { // 处理keydown事件 function dispatch(event) { + // console.log('option:1', event); const asterisk = _handlers['*']; let key = event.keyCode || event.which || event.charCode; @@ -195,7 +196,9 @@ function dispatch(event) { // 对任何快捷键都需要做的处理 if (asterisk) { for (let i = 0; i < asterisk.length; i++) { - if (asterisk[i].scope === scope) eventHandler(event, asterisk[i], scope); + if (asterisk[i].scope === scope && (event.type === 'keydown' || (event.type === 'keyup' && asterisk[i].keyup))) { + eventHandler(event, asterisk[i], scope); + } } } // key 不在_handlers中返回 @@ -240,8 +243,8 @@ function hotkeys(key, option, method) { // 判断key是否在_handlers中,不在就赋一个空数组 if (!(key in _handlers)) _handlers[key] = []; - _handlers[key].push({ + keyup: option.keyup || false, scope, mods, shortcut: keys[i], @@ -256,6 +259,7 @@ function hotkeys(key, option, method) { dispatch(e); }); addEvent(element, 'keyup', (e) => { + dispatch(e); clearModifier(e); }); }