HotKeys.js 是一个具有一些非常特殊功能的输入捕获库,它易于上手和使用,占用空间合理(~8kB)(压缩后:3.8kB),无依赖。它不应该干扰任何 JavaScript 库或框架。官方文档 演示预览,兼容性测试。更多示例。
╭┈┈╮ ╭┈┈╮ ╭┈┈╮
┆ ├┈┈..┈┈┈┈┈.┆ └┈╮┆ ├┈┈..┈┈┈┈┈..┈┈.┈┈..┈┈┈┈┈.
┆ ┆┆ □ ┆┆ ┈┤┆ < ┆ -__┘┆ ┆ ┆┆__ ┈┈┤
╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈┈╯╰┈┈┴┈┈╯╰┈┈┈┈┈╯╰┈┈┈ ┆╰┈┈┈┈┈╯
╰┈┈┈┈┈╯您的系统需要安装 Node.js。
npm install hotkeys-js --saveimport hotkeys from 'hotkeys-js';
hotkeys('f5', function(event, handler){
// 阻止 WINDOWS 系统下的默认刷新事件
event.preventDefault()
alert('你按下了 F5!')
});或者手动下载并在 HTML 中链接 hotkeys.js。该库提供了不同格式以满足不同的使用需求:
CDN 链接: UNPKG | jsDelivr | Githack | Statically
可用格式:
IIFE(立即调用函数表达式)- 推荐用于直接浏览器使用:
<script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.min.js">
</script>
<script type="text/javascript">
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);
}
});
</script>UMD(通用模块定义)- 用于 CommonJS/AMD 环境:
<script src="https://unpkg.com/hotkeys-js/dist/hotkeys-js.umd.cjs">
</script>ES 模块 - 用于支持模块的现代浏览器:
<script type="module">
import hotkeys from 'https://unpkg.com/hotkeys-js/dist/hotkeys-js.js';
hotkeys('ctrl+a', function(event, handler){
alert('你按下了 ctrl+a!');
});
</script>react-hotkeys 是监听 keydown 和 keyup 键盘事件的 React 组件,定义和调度键盘快捷键。详细的使用方法请查看其文档 react-hotkeys。
react-hotkeys-hook - 在组件中使用键盘快捷键的 React hook。请确保您至少安装了 react 和 react-dom 的 16.8 版本,否则 hooks 将不会为您工作。
Hotkeys.js 已经过测试,应该在以下浏览器中工作。
Internet Explorer 6+
Safari
Firefox
ChromeHotKeys 理解以下修饰符:⇧、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
暴露了一个全局方法,当直接调用时定义快捷键。
declare interface HotkeysInterface extends HotkeysAPI {
(key: string, method: KeyHandler): void;
(key: string, scope: string, method: KeyHandler): void;
(key: string, option: HotkeysOptions, method: KeyHandler): void;
shift?: boolean;
ctrl?: boolean;
alt?: boolean;
option?: boolean;
control?: boolean;
cmd?: boolean;
command?: boolean;
}
declare interface HotkeysAPI {
setScope: SetScope;
getScope: GetScope;
deleteScope: DeleteScope;
getPressedKeyCodes: GetPressedKeyCodes;
getPressedKeyString: GetPressedKeyString;
getAllKeyCodes: GetAllKeyCodes;
isPressed: IsPressed;
filter: Filter;
trigger: Trigger;
unbind: Unbind;
noConflict: NoConflict;
keyMap: Record<string, number>;
modifier: Record<string, number>;
modifierMap: Record<string | number, number | string>;
}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);
});scope<String>:设置快捷键生效的作用域element<HTMLElement>:指定要绑定事件的 DOM 元素keyup<Boolean>:是否在按键释放时触发快捷键keydown<Boolean>:是否在按键按下时触发快捷键splitKey<String>:组合键的分隔符(默认为+)capture<Boolean>:是否在捕获阶段触发监听器(在事件冒泡之前)single<Boolean>:只允许一个回调函数(自动解绑之前的)
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
按键按下 和 按键释放 都执行回调事件。
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);
}
});星号 "*"
修饰键判断
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!');
}
});使用 hotkeys.setScope 方法来设置作用域。除了 'all' 之外,只能有一个活动作用域。默认情况下 'all' 总是活动的。
// 定义带有作用域的快捷键
hotkeys('ctrl+o, ctrl+alt+enter', 'issues', function() {
console.log('做一些事情');
});
hotkeys('o, enter', 'files', function() {
console.log('做其他事情');
});
// 设置作用域(只有 'all' 和 'issues' 快捷键会被处理)
hotkeys.setScope('issues'); // 默认作用域是 'all'使用 hotkeys.getScope 方法来获取作用域。
hotkeys.getScope();使用 hotkeys.deleteScope 方法来删除作用域。这也会移除与之关联的所有热键。
hotkeys.deleteScope('issues');如果需要在删除后设置新的作用域,可以使用第二个参数。
hotkeys.deleteScope('issues', 'newScopeName');与定义快捷键类似,它们可以使用 hotkeys.unbind 来解绑。
// 解绑 'a' 处理器
hotkeys.unbind('a');
// 只为单个作用域解绑热键
// 如果没有指定作用域,默认为当前作用域
// (hotkeys.getScope())
hotkeys.unbind('o, enter', 'issues');
hotkeys.unbind('o, enter', 'files');通过函数解绑事件。
function example() {
hotkeys('a', example);
hotkeys.unbind('a', example);
hotkeys('a', 'issues', example);
hotkeys.unbind('a', 'issues', example);
}解绑所有。
hotkeys.unbind();例如,如果当前按下了 M 键,hotkeys.isPressed(77) 返回 true。
hotkeys('a', function() {
console.log(hotkeys.isPressed('a')); //=> true
console.log(hotkeys.isPressed('A')); //=> true
console.log(hotkeys.isPressed(65)); //=> true
});触发快捷键事件
hotkeys.trigger('ctrl+o');
hotkeys.trigger('ctrl+o', 'scope2');返回当前按下的键码数组。
hotkeys('command+ctrl+shift+a,f', function() {
console.log(hotkeys.getPressedKeyCodes()); //=> [17, 65] 或 [70]
})返回当前按下的键字符串数组。
hotkeys('command+ctrl+shift+a,f', function() {
console.log(hotkeys.getPressedKeyString());
//=> ['⌘', '⌃', '⇧', 'A', 'F']
})获取所有注册码的列表。
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] }
// ]
})默认情况下,INPUT SELECT TEXTAREA 元素不启用热键。Hotkeys.filter 返回 true 快捷键设置发挥作用,false 快捷键设置失败。
hotkeys.filter = function(event){
return true;
}
// 如何为编辑标签添加过滤器。
// <div contentEditable="true"></div>
// "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;
}放弃 HotKeys 对 hotkeys 变量的控制。
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要开发,需要安装依赖,获取代码:
$ git https://github.com/jaywcjlove/hotkeys.git
$ cd hotkeys # 进入目录
$ npm install # 或者 yarn install要开发,运行自重载构建:
$ npm run watch运行文档网站环境。
$ npm run doc # 生成文档网页
# 实时生成文档网页
$ npm run start 要贡献,请 fork Hotkeys.js,添加您的补丁和测试(在 test/ 文件夹中)并提交拉取请求。
$ npm run test
$ npm run test:watch # 开发模式一如既往,感谢我们出色的贡献者!
使用 action-contributors 制作。