master
宇天 2020-10-30 17:18:08 +08:00
parent cd47cd008a
commit 638abf798d
4 changed files with 64 additions and 5 deletions

View File

@ -1,2 +1,5 @@
## JS键盘热键
> 支持各种按钮组合。
![keyboard](./keyboardjpg)

BIN
keyboard.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

@ -4,16 +4,18 @@
* @date 2020/10/29 16:48:26
*/
import KEY_DICT from './key.dict.js'
import { KEY_DICT, MULTI_KEYS } from './key.dict.js'
var log = console.log
function keydown(ev) {
var { code, keyCode } = ev
// log(ev.keyCode, ev.code, KEYCODE_DICT[keyCode])
log(ev.keyCode, ev.code, ev.target)
}
function createCheckFunc(act) {}
export default class Keyboard {
constructor() {
this.__EVENTS__ = {}
@ -25,7 +27,52 @@ export default class Keyboard {
document.removeEventListener('keydown', keydown, false)
}
on(action, callback) {
//
on(act, callback) {
var key = []
var dict = []
act.forEach(it => {
var tmp = {}
dict.push(tmp)
it = it.split('+').map(k => {
k = k.trim().toLowerCase()
tmp[k] = KEY_DICT[k]
return k
})
key.push(it.join('+'))
})
key = key.join(',')
if (this.__EVENTS__[key]) {
this.__EVENTS__[key].fn.push(callback)
} else {
this.__EVENTS__[key] = {
dict,
check(ev) {
var { keyCode, code } = ev
var now = 0
var actions = this.dict.concat()
var action = actions.shift()
var checked = false
while (action) {
if (now === 0) {
} else {
var _now = Date.now()
if (_now - now > 100) {
checked = false
break
}
now = _now
}
}
return checked
},
fn: [callback]
}
}
log(this.__EVENTS__)
}
}

View File

@ -1,4 +1,13 @@
export default {
// 允许组合出现的辅助键
export const MULTI_KEYS = {
ctrl: 1,
shift: 1,
alt: 1,
super: 1
}
// 按键对应的code值
export const KEY_DICT = {
'0': 48, // Digit{N}, Numpad{N}
'1': 49,
'2': 50,