# hotkeys **Repository Path**: jaywcjlove/hotkeys ## Basic Information - **Project Name**: hotkeys - **Description**: js简单的设置快捷键,没有依赖。 https://jaywcjlove.gitee.io/hotkeys - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: https://jaywcjlove.gitee.io/hotkeys - **GVP Project**: No ## Statistics - **Stars**: 150 - **Forks**: 27 - **Created**: 2015-05-19 - **Last Updated**: 2025-11-15 ## Categories & Tags **Categories**: javascript-toolkits **Tags**: None ## README
使用我的应用也是一种支持我的方式:
Keyzer Vidwall Hub VidCrop Vidwall Mousio Hint Mousio Musicer Audioer FileSentinel FocusCursor Videoer KeyClicker DayBar Iconed Mousio Quick RSS Quick RSS Web Serve Copybook Generator DevTutor for SwiftUI RegexMate Time Passage Iconize Folder Textsound Saver Create Custom Symbols DevHub Resume Revise Palette Genius Symbol Scribe

# Hotkeys [![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-048754?logo=buymeacoffee)](https://jaywcjlove.github.io/#/sponsor) [![](https://img.shields.io/npm/dm/hotkeys-js?logo=npm)](https://www.npmjs.com/package/hotkeys-js) [![](https://img.shields.io/github/stars/jaywcjlove/hotkeys-js.svg)](https://github.com/jaywcjlove/hotkeys/stargazers) ![no dependencies](http://jaywcjlove.github.io/sb/status/no-dependencies.svg) [![GitHub Actions CI](https://github.com/jaywcjlove/hotkeys-js/actions/workflows/ci.yml/badge.svg)](https://github.com/jaywcjlove/hotkeys-js/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/jaywcjlove/hotkeys/badge.svg?branch=master)](https://coveralls.io/github/jaywcjlove/hotkeys?branch=master) [![English](https://jaywcjlove.github.io/sb/lang/english.svg)](https://jaywcjlove.github.io/hotkeys-js/) [![jaywcjlove/hotkeys-js](https://jaywcjlove.github.io/sb/ico/gitee.svg)](https://gitee.com/jaywcjlove/hotkeys) HotKeys.js 是一个具有一些非常特殊功能的输入捕获库,它易于上手和使用,占用空间合理([~6kB](https://bundlephobia.com/result?p=hotkeys-js))(压缩后:**`2.8kB`**),无依赖。它不应该干扰任何 JavaScript 库或框架。官方文档 [演示预览](https://jaywcjlove.github.io/hotkeys-js)。[更多示例](https://github.com/jaywcjlove/hotkeys-js/issues?q=label%3ADemo+)。 ```bash ╭┈┈╮ ╭┈┈╮ ╭┈┈╮ ┆ ├┈┈..┈┈┈┈┈.┆ └┈╮┆ ├┈┈..┈┈┈┈┈..┈┈.┈┈..┈┈┈┈┈. ┆ ┆┆ □ ┆┆ ┈┤┆ < ┆ -__┘┆ ┆ ┆┆__ ┈┈┤ ╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈┈╯╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈ ┆╰┈┈┈┈┈╯ ╰┈┈┈┈┈╯ ``` ## 使用 您的系统需要安装 `Node.js`。 ```bash npm install hotkeys-js --save ``` ```js import hotkeys from 'hotkeys-js'; hotkeys('f5', function(event, handler){ // 阻止 WINDOWS 系统下的默认刷新事件 event.preventDefault() alert('你按下了 F5!') }); ``` 或者手动下载并在 HTML 中链接 **hotkeys.js**,也可以通过 [UNPKG](https://unpkg.com/hotkeys-js/dist/) 下载: CDN: [UNPKG](https://unpkg.com/hotkeys-js/dist/) | [jsDelivr](https://cdn.jsdelivr.net/npm/hotkeys-js/) | [Githack](https://raw.githack.com/jaywcjlove/hotkeys/master/dist/hotkeys-js.umd.cjs) | [Statically](https://cdn.statically.io/gh/jaywcjlove/hotkeys/master/dist/hotkeys-js.umd.cjs) | [bundle.run](https://bundle.run/hotkeys-js@3.7.3) ```html ``` ### 在 React 中使用 [react-hotkeys](https://github.com/jaywcjlove/react-hotkeys) 是监听 keydown 和 keyup 键盘事件的 React 组件,定义和调度键盘快捷键。详细的使用方法请查看其文档 [react-hotkeys](https://github.com/jaywcjlove/react-hotkeys)。 [react-hotkeys-hook](https://github.com/JohannesKlauss/react-hotkeys-hook) - 在组件中使用键盘快捷键的 React hook。请确保您至少安装了 react 和 react-dom 的 16.8 版本,否则 hooks 将不会为您工作。 ## 浏览器支持 Hotkeys.js 已经过测试,应该在以下浏览器中工作。 ```shell Internet Explorer 6+ Safari Firefox Chrome ``` ## 支持的按键 HotKeys 理解以下修饰符:`⇧`、`shift`、`option`、`⌥`、`alt`、`ctrl`、`control`、`command` 和 `⌘`。 以下特殊按键可用于快捷键:backspace、tab、clear、enter、return、esc、escape、space、up、down、left、right、home、end、pageup、pagedown、del、delete、f1 到 f19、num_0 到 num_9、num_multiply、num_add、num_enter、num_subtract、num_decimal、num_divide。 `⌘` Command() `⌃` Control `⌥` Option(alt) `⇧` Shift `⇪` Caps Lock(Capital) ~~`fn` 不支持 fn~~ `↩︎` return/Enter space ## 定义快捷键 暴露了一个全局方法,当直接调用时定义快捷键。 ```js hotkeys([keys:], [option:[string|object|function]], [callback:]) ``` ```js hotkeys('f5', function(event, handler) { // 阻止 WINDOWS 系统下的默认刷新事件 event.preventDefault(); alert('你按下了 F5!'); }); // 返回 false 停止事件并阻止默认浏览器事件 // Mac OS 系统将 `command + r` 定义为刷新快捷键 hotkeys('ctrl+r, command+r', function() { alert('停止刷新!'); return false; }); // 单个按键 hotkeys('a', function(event,handler){ //event.srcElement: input //event.target: input if(event.target === "input"){ alert('你按下了 a!') } alert('你按下了 a!') }); // 组合键 hotkeys('ctrl+a,ctrl+b,r,f', function (event, handler){ switch (handler.key) { case 'ctrl+a': alert('你按下了 ctrl+a!'); break; case 'ctrl+b': alert('你按下了 ctrl+b!'); break; case 'r': alert('你按下了 r!'); break; case 'f': alert('你按下了 f!'); break; default: alert(event); } }); hotkeys('ctrl+a+s', function() { alert('你按下了 ctrl+a+s!'); }); // 使用作用域 hotkeys('*','wcj', function(event){ console.log('做一些事情', event); }); ``` #### option 选项 - `scope`:设置快捷键生效的作用域 - `element`:指定要绑定事件的 DOM 元素 - `keyup`:是否在按键释放时触发快捷键 - `keydown`:是否在按键按下时触发快捷键 - `splitKey`:组合键的分隔符(默认为 `+`) - `capture`:是否在捕获阶段触发监听器(在事件冒泡之前) - `single`:只允许一个回调函数(自动解绑之前的) ```js hotkeys('o, enter', { scope: 'wcj', element: document.getElementById('wrapper'), }, function() { console.log('做其他事情'); }); hotkeys('ctrl-+', { splitKey: '-' }, function(e) { console.log('你按下了 ctrl 和 +'); }); hotkeys('+', { splitKey: '-' }, function(e){ console.log('你按下了 +'); }) ``` **keyup** **按键按下** 和 **按键释放** 都执行回调事件。 ```js hotkeys('ctrl+a,alt+a+s', {keyup: true}, function(event, handler) { if (event.type === 'keydown') { console.log('keydown:', event.type, handler, handler.key); } if (event.type === 'keyup') { console.log('keyup:', event.type, handler, handler.key); } }); ``` ## API 参考 星号 "*" 修饰键判断 ```js hotkeys('*', function() { if (hotkeys.shift) { console.log('按下了 shift!'); } if (hotkeys.ctrl) { console.log('按下了 ctrl!'); } if (hotkeys.alt) { console.log('按下了 alt!'); } if (hotkeys.option) { console.log('按下了 option!'); } if (hotkeys.control) { console.log('按下了 control!'); } if (hotkeys.cmd) { console.log('按下了 cmd!'); } if (hotkeys.command) { console.log('按下了 command!'); } }); ``` ### setScope 使用 `hotkeys.setScope` 方法来设置作用域。除了 'all' 之外,只能有一个活动作用域。默认情况下 'all' 总是活动的。 ```js // 定义带有作用域的快捷键 hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function() { console.log('做一些事情'); }); hotkeys('o, enter', 'files', function() { console.log('做其他事情'); }); // 设置作用域(只有 'all' 和 'issues' 快捷键会被处理) hotkeys.setScope('issues'); // 默认作用域是 'all' ``` ### getScope 使用 `hotkeys.getScope` 方法来获取作用域。 ```js hotkeys.getScope(); ``` ### deleteScope 使用 `hotkeys.deleteScope` 方法来删除作用域。这也会移除与之关联的所有热键。 ```js hotkeys.deleteScope('issues'); ``` 如果需要在删除后设置新的作用域,可以使用第二个参数。 ```js hotkeys.deleteScope('issues', 'newScopeName'); ``` ### unbind 与定义快捷键类似,它们可以使用 `hotkeys.unbind` 来解绑。 ```js // 解绑 'a' 处理器 hotkeys.unbind('a'); // 只为单个作用域解绑热键 // 如果没有指定作用域,默认为当前作用域(hotkeys.getScope()) hotkeys.unbind('o, enter', 'issues'); hotkeys.unbind('o, enter', 'files'); ``` 通过函数解绑事件。 ```js function example() { hotkeys('a', example); hotkeys.unbind('a', example); hotkeys('a', 'issues', example); hotkeys.unbind('a', 'issues', example); } ``` 解绑所有。 ```js hotkeys.unbind(); ``` ### isPressed 例如,如果当前按下了 `M` 键,`hotkeys.isPressed(77)` 返回 true。 ```js hotkeys('a', function() { console.log(hotkeys.isPressed('a')); //=> true console.log(hotkeys.isPressed('A')); //=> true console.log(hotkeys.isPressed(65)); //=> true }); ``` ### trigger 触发快捷键事件 ```js hotkeys.trigger('ctrl+o'); hotkeys.trigger('ctrl+o', 'scope2'); ``` ### getPressedKeyCodes 返回当前按下的键码数组。 ```js hotkeys('command+ctrl+shift+a,f', function() { console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] 或 [70] }) ``` ### getPressedKeyString 返回当前按下的键字符串数组。 ```js hotkeys('command+ctrl+shift+a,f', function() { console.log(hotkeys.getPressedKeyString()); //=> ['⌘', '⌃', '⇧', 'A', 'F'] }) ``` ### getAllKeyCodes 获取所有注册码的列表。 ```js hotkeys('command+ctrl+shift+a,f', function() { console.log(hotkeys.getAllKeyCodes()); // [ // { scope: 'all', shortcut: 'command+ctrl+shift+a', mods: [91, 17, 16], keys: [91, 17, 16, 65] }, // { scope: 'all', shortcut: 'f', mods: [], keys: [42] } // ] }) ``` ### filter 默认情况下,`INPUT` `SELECT` `TEXTAREA` 元素不启用热键。`Hotkeys.filter` 返回 `true` 快捷键设置发挥作用,`false` 快捷键设置失败。 ```js hotkeys.filter = function(event){ return true; } //如何为编辑标签添加过滤器。
//"contentEditable" 不支持的较旧浏览器会被丢弃 hotkeys.filter = function(event) { var target = event.target || event.srcElement; var tagName = target.tagName; return !(target.isContentEditable || tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA'); } hotkeys.filter = function(event){ var tagName = (event.target || event.srcElement).tagName; hotkeys.setScope(/^(INPUT|TEXTAREA|SELECT)$/.test(tagName) ? 'input' : 'other'); return true; } ``` ### noConflict 放弃 HotKeys 对 `hotkeys` 变量的控制。 ```js var k = hotkeys.noConflict(); k('a', function() { console.log("做一些事情") }); hotkeys() // -->Uncaught TypeError: hotkeys is not a function(anonymous function) // @ VM2170:2InjectedScript._evaluateOn // @ VM2165:883InjectedScript._evaluateAndWrap // @ VM2165:816InjectedScript.evaluate @ VM2165:682 ``` ## 开发 要开发,需要安装依赖,获取代码: ```shell $ git https://github.com/jaywcjlove/hotkeys.git $ cd hotkeys # 进入目录 $ npm install # 或者 yarn install ``` 要开发,运行自重载构建: ```shell $ npm run watch ``` 运行文档网站环境。 ```shell $ npm run doc ``` 要贡献,请 fork Hotkeys.js,添加您的补丁和测试(在 `test/` 文件夹中)并提交拉取请求。 ```shell $ npm run test $ npm run test:watch # 开发模式 ``` ## 贡献者 一如既往,感谢我们出色的贡献者! 使用 [action-contributors](https://github.com/jaywcjlove/github-action-contributors) 制作。 特别感谢 [@dimensi](https://github.com/dimensi) 对版本 [4.0](https://github.com/jaywcjlove/hotkeys-js/issues/313) 的重构。 ## 许可证 [MIT © Kenny Wong](./LICENSE)