@gluttons/keywatch
v0.0.4
Published
用户按键输入观察
Readme
KeyWatch
按键观察
安装
npm i @gluttons/keywatch -S
使用
import { KeyWatch } from '@gluttons/keywatch';
const keyWatch = new KeyWatch();
// 监听
const removeListen = keyWatch.listen('ctrl+c', () => {
console.log('复制');
// 返回 true 禁用浏览器默认行为
return true;
});
// 移除
removeListen();
// 全局阻止默认行为
const keyWatch = new KeyWatch({
preventDefault: true,
});
/**
* 组合键
* 先按下 ctrl+k,再按下 ctrl+u
**/
keyWatch.listen('ctrl+k>ctrl+u', () => {
console.log('将文本转换为大写');
return true;
});
// 监听多个
keyWatch.listen(['ctrl+z', 'ctrl+a'], () => {
console.log('撤销');
});监听文本输入框
<input id="input" />const keyWatch = new KeyWatch({
target: document.querySelector('#input'),
});
// 监听所有按键
keyWatch.listen((event) => {
console.log(`按下了${event.key}`);
});判断
// 是否按下 ctrl 键
console.log(keyWatch.ctrl);
// 是否按下 shift 键
console.log(keyWatch.shift);
// 是否按下 alt 键
console.log(keyWatch.alt);
// 是否按下 meta 键
console.log(keyWatch.meta);
// 判断其他按键
console.log(keyWatch.isPressed('a'));
// 判断多个按键
console.log(keyWatch.isPressed(['a', 'b'])); // 需同时按下才为 truestrict 严格模式
当观察对象是 window 或 document 时为全局按键观察,当焦点在 input 、button 等元素时按下按键也会触发全局按键观察,开启严格模式后将不会触发,默认开启
// 关闭严格模式
const keyWatch = new KeyWatch({
strict: false,
});