之前在学electron时,
想做一个大部分操作都可以脱离鼠标的应用。
这就涉及到需要很多的快捷键来使用,
所以一自己封装了一个方法,来快速注册(组合)快捷键;
使用起来也比较简单:
npm install web_shortcutimport web_shortcut from 'web_shortcut';
const $_shortcut = web_shortcut();
$_shortcut.init(
inputDom,
{
common: {
enter: () => {console.log('您键入了enter');},
esc: () => {console.log('您键入了 esc');}
},
alt: {
13: () => {console.log('您键入了alt + enter');},
},
ctrl_alt: {
13: () => {console.log('您键入了 ctrl + alt + enter');},
}
}
);原理是绑定了 传入的节点的 onkeydown 事件
然后 根据 事件对象的 ev.ctrlKey, ev.altKey, ev.shiftKey 来判断是否组合按键
按照上述顺序 拼接 ctrl _alt _shift, + ev.which 来确定需要调用的方法。
奉上核心源码
其中的 keyMap 做了一个对照表 比如 up => 38, enter => 13;
目前版本没做兼容性... 比如 event 对象, es6 之后的写法,querySelector 等方法
const ShortCut = function(){this.maps = {}}
ShortCut.prototype.init = function(dom, fns){
const $body = dom || document.querySelector("body");
$body.onkeydown = ev => {
let key = '';
if (ev.ctrlKey){
key += key ? '_ctrl' : 'ctrl';
}
if (ev.altKey){
key += key ? '_alt' : 'alt';
}
if (ev.shiftKey) {
key += key ? '_shift' : 'shift';
}
const cmd = `this.maps.${key || 'common'}[${ev.which}](ev)`;
try {
eval(cmd);
} catch (e) {
}
};
if (fns){
getType.isObject(fns) && Object.keys(fns).forEach(key => {
fns[key] && Object.keys(fns[key]).forEach(item => this[key](item, fns[key][item]));
});
}
};
function makeShortCutInitFn(key) {
ShortCut.prototype[key] || (
ShortCut.prototype[key] = function (keyNum, cb) {
getType.isNumber(keyNum) || (keyNum = keyMap[keyNum] || keyNum);
this.maps[key] || (this.maps[key] = {});
this.maps[key][keyNum] = (ev) => {cb(); ev.stopPropagation();ev.preventDefault();}
}
)
};
['common', 'ctrl', 'alt', 'shift', 'ctrl_alt', 'ctrl_shift', 'alt_shift','ctrl_alt_shift',]
.forEach(makeShortCutInitFn);github github.com/DeyaoCai/we…
npm www.npmjs.com/package/web…