开发者

JQuery Hotkeys - binding to multiple alphanumeric character combinations

I am using the latest version of JQuery hotkeys.

The plug-in is fantastic and, in the main, does exactly what I need it to do.

However, I would like to bind to a combination of keys such as "A+H",开发者_JAVA百科 for example:

jQuery(document).bind('keydown', 'a+h', function(evt) { alert('hello world!'); }

This doesn't seem to work - has anyone acheived this succesfully? CTRL+A, etc. works, but it would be ideal if i could bind to combinations of alpha-numeric characters.


I took a look at the code base and it looks like the way that plugin is programmed, it will not support the use case you're describing. It lumps the modifier keys (shift, alt, etc.) together as a special case, which allows you to create combinations involving mod keys. It doesn't support multiple standard keys, however.

I would suggest you ask the plugin developer to add this feature in a future release. In the mean time, you can either adapt your goals to fit this plugin, try modifying the plugin yourself, or write custom code for this special case.

By the way, the code isn't particularly complicated so you should definitely take a gander. Maybe you'll see something I don't.
The plugin file.


I don't think this would be possible to detect both keys since pressing any key will only fire off one event. Shift, alt, ctrl and other meta keys are a special case.

One solution would be to save the last key pressed then wait for the next one. I made a demo of the code below:

var timer, last;
$(document).bind('keydown', function(e) {
    // Typing a then h will call the alert
    if (last == 65 && e.which === 72) {
        alert('Hello World');
    }
    last = e.which;
    // clear last value after 100 ms
    clearTimeout(timer);
    timer = setTimeout(function(){
        last = '';
    }, 100);
}); 

Notice the last key is cleared after 100 milliseconds because without it, you could press "a" then wait something like 10 seconds, then press "h" to get the alert. Now the combination has to be pressed almost together (but the "a" has to be before the "h") - a slight modification would also allow the user to press "h" first then "a".


It's not exactly what you request but this works for a then h instead of a+h (which is awkard to do on your keyboard)

$(document).bind('keyup', 'a', function(){
    $(document).bind('keyup', 'h', function(){
        // do you shizzle
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜