如何在jquery中绑定组合键ctrl + x + return [英] how to bind key combination ctrl+x+return in jquery
问题描述
有没有办法在jquery(或javascript)中捕获组合键 ctrl + x + return ,这样如果用户按此键组合键,调用一个函数。我尝试使用jquery hotkeys插件,但是没有用。
Is there any way to catch key combination ctrl+x+return in jquery(or javascript), such that if user presses this key combination, a function is called. I tried using the jquery hotkeys plugin, but that didn't worked.
推荐答案
使用全局布尔数组 var keys = []
检查是否按下了某个键。然后使用以下函数添加全局热键:
Use a global boolean array var keys = []
to check whether a key is pressed. Then use the following function to add a global hotkey:
window.addGlobalHotkey = function(callback,keyValues){
if(typeof keyValues === "number")
keyValues = [keyValues];
var fnc = function(cb,val){
return function(e){
keys[e.keyCode] = true;
executeHotkeyTest(cb,val);
};
}(callback,keyValues);
window.addEventListener('keydown',fnc);
return fnc;
};
正如您所看到的,它为'keydown'<添加了一个新的监听器/ code>事件。此侦听器将首先在
keys
中设置相应的值,然后执行测试,无论给定的 keyValues
当前是否为true 。请注意,您无法删除 keys [e.keyCode] = true
并将其放在另一个侦听器中,因为这可能会导致错误的回调顺序(首先是热键测试,然后是键映射) 。 executeHotkeyTest
本身也非常简单:
As you can see it adds a new listener to the 'keydown'
event. This listener will first set the corresponding value in keys
true and then execute a test, whether the given keyValues
are currently true. Note that you cannot remove keys[e.keyCode] = true
and put it in another listener because this could result in a wrong callback order (first hotkey testing, then key mapping). The executeHotkeyTest
itself is very easy too:
window.executeHotkeyTest = function(callback,keyValues){
var allKeysValid = true;
for(var i = 0; i < keyValues.length; ++i)
allKeysValid = allKeysValid && keys[keyValues[i]];
if(allKeysValid)
callback();
};
最后你必须添加另一个监听器 keyup
从键清除已释放的键
。
At last you have to add another listener to keyup
to clean the released keys from keys
.
window.addEventListener('keyup',function(e){
keys[e.keyCode] = false;
});
现在可以使用 addGlobalHotkey将热键添加到ctrl + x + enter (回调,[13,17,88])
:
addGlobalHotkey(function(){
document.body.appendChild(
document.createElement('div').appendChild(
document.createTextNode('Ctrl + x + Enter down')
).parentNode);
},[88,13,17]);
JSFiddle demo
您可以使用全局而不是为每个热键添加一个监听器[[callback1,values1],[callback2,values2],...]
array。
Instead of adding a listener for every hotkey you can use a global [[callback1,values1],[callback2,values2],...]
array.
重要提示 :在IE早期版本9中,您必须使用 attachEvent
而不是 addEventListener
。由于您已经在使用jQuery,因此可以使用 .on(...)
或 .keydown
。
Important note: in IE prior version 9 you have to use attachEvent
instead of addEventListener
. Since you're already using jQuery you could use .on(...)
or .keydown
instead.
这篇关于如何在jquery中绑定组合键ctrl + x + return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!