JavaScript Key Binding Library
此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.org/scripts/23404/149412/keyboard-js.js
A little library for keyboard binding. Now, it just supports chrome.
If you want to support more browsers or nodejs platform, just fork it.
Have fun, XD.
Full list of key values
Now, you can try it here. (source)
And, you can find which key(key combo will print on the console.) do you press at that page, when you find your code didn't run.
var Keyboard = require('keyboard-js').Keyboard
var keyboard = new Keyboard() // pay more attention: singal instance
// start to listen
keyboard.start()
// register
// when you hit <kbd>Shift+e</kbd> or <kbd>Ctrl+e</kbd> that will print `> test uk successfully`.
keyboard.register('uk', function (event) {
// event.preventDefault()
// event.stopPropagation()
// event.stopImmediatePropagation()
console.log('test uk successfully.')
// event.clearKeys() // if you use function::alert or function::confirm
}, ["Shift", "E"], ["Control", "e"]) // attention: Shift E (not e)
// have fun :)
Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed
This key combo keeps activating even though I'm not pressing the keys
event.clearKeys()
in the callbackOMG! Please forgive me.
Please pay more attention to the key combo. You should avoid the key conflict. For example, if you registe the Shortcut Key: Shift + B, you will be confused when you hit Shift + B in the textarea. So, be careful.
However, you can use API::Keyboard.end()
to end when the textarea is focused
and use API::Keyboard.start()
to restart when it blurs.
Also, you can discard the Shortcut Key: Shift + B.
Constructor Options
{
DEBUG: [boolen], // default: false. If true, it will print key message on the console.
element: [DOM Element], // default: document. Use this to listen the keydown or keyup.
}
Exposed Interface:
Keyboard.start(): start to listen the keypress event
Keyboard.end(): end to listen keypress event and clean some resource
Keyboard.register(name:String, callback:Function, [key1:String, key2:String,...], ...): registe the keyboard binding
Keyboard.unregister(name:String): remove the register by name
And the callback defination:
// callback
function callback (event) {
// event.preventDefault()
// event.stopPropagation()
// event.stopImmediatePropagation()
// your code here
// ...
// event.clearKeys() // if you use function::alert or function::confirm
}
If you find bugs or have any questions, you can submit them to the github issues.
MIT