diff --git a/README.md b/README.md index c64b86b..566292b 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,7 @@ hotkeys('*','wcj', function(event){ - `keyup` - `keydown` - `splitKey` (default is `+`) +- `capture` ```js hotkeys('o, enter', { diff --git a/index.d.ts b/index.d.ts index 7488500..749f1a8 100644 --- a/index.d.ts +++ b/index.d.ts @@ -15,6 +15,7 @@ type Options = { element?: HTMLElement | null; keyup?: boolean | null; keydown?: boolean | null; + capture?: boolean splitKey?: string; } diff --git a/src/index.js b/src/index.js index 5a37bfc..e937b2a 100644 --- a/src/index.js +++ b/src/index.js @@ -325,6 +325,7 @@ function hotkeys(key, option, method) { let keyup = false; let keydown = true; let splitKey = '+'; + let capture = false; // 对为设定范围的判断 if (method === undefined && typeof option === 'function') { @@ -336,6 +337,7 @@ function hotkeys(key, option, method) { if (option.element) element = option.element; // eslint-disable-line if (option.keyup) keyup = option.keyup; // eslint-disable-line if (option.keydown !== undefined) keydown = option.keydown; // eslint-disable-line + if (option.capture !== undefined) capture = option.capture; // eslint-disable-line if (typeof option.splitKey === 'string') splitKey = option.splitKey; // eslint-disable-line } @@ -372,17 +374,17 @@ function hotkeys(key, option, method) { elementHasBindEvent.push(element); addEvent(element, 'keydown', (e) => { dispatch(e, element); - }); + }, capture); if (!winListendFocus) { winListendFocus = true; addEvent(window, 'focus', () => { _downKeys = []; - }); + }, capture); } addEvent(element, 'keyup', (e) => { dispatch(e, element); clearModifier(e); - }); + }, capture); } } diff --git a/src/utils.js b/src/utils.js index fd8d8c9..b182cb6 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,9 +1,9 @@ const isff = typeof navigator !== 'undefined' ? navigator.userAgent.toLowerCase().indexOf('firefox') > 0 : false; // 绑定事件 -function addEvent(object, event, method) { +function addEvent(object, event, method, useCapture) { if (object.addEventListener) { - object.addEventListener(event, method, false); + object.addEventListener(event, method, useCapture); } else if (object.attachEvent) { object.attachEvent(`on${event}`, () => { method(window.event); }); } diff --git a/test/run.test.js b/test/run.test.js index 44c9667..be17f18 100644 --- a/test/run.test.js +++ b/test/run.test.js @@ -646,6 +646,23 @@ describe('\n Hotkeys.js Test Case222.\n', () => { }); }); + test('Hotkey modifier capture', async () => { + let isExecuteFunction = false; + const el = document.createElement('div'); + + el.addEventListener('keydown', () => { + isExecuteFunction = true; + }); + + await hotkeys('a', { capture: true, element: el }, (event) => { + event.stopImmediatePropagation(); + }); + + __triggerKeyboardEvent(el, 65); + expect(isExecuteFunction).toBeFalsy(); + await hotkeys.unbind('a'); + }); + afterAll(async () => { await browser.close(); });