AngularJS - 同时按下多个按键 [英] AngularJS - Multiple keypress at the same time
问题描述
我有以下 $broadcast
来捕捉 Angular 中的按键:
I have the following $broadcast
to catch keypresses in Angular:
$document.bind('keypress', function(event) {
var key = event.which;
$rootScope.$broadcast('keypress', event);
$rootScope.$broadcast('keypress:' + key, event);
});
我用 $on
但是,我想检测两个键何时被同时按下,比如 enter
和 s
被同时按下(不是一个一个的组合由另一个).
However, I want to detect when two keys are pressed at the same time, say enter
and s
are pressed at the same time (not a combination one one followed by another).
这样做的最佳方法是什么?
What is the best way of doing this?
编辑
我的想法是:
var keys = [];
$document.bind('keydown', function(event) {
keys[event.which] = true;
});
$document.bind('keyup', function(event) {
delete keys[event.which];
});
$document.bind('keypress', function(event) {
var key = event.which;
var keysPressed = [];
angular.forEach(keys, function(value, key) {
keysPressed += 'keypress:' + key;
});
$rootScope.$broadcast('keypress', event);
$rootScope.$broadcast(keysPressed, event);
});
因此,如果我有多个按键,那么我会创建正确的 $broadcast
.然而,问题变成了现在的顺序很重要(即,如果我按 a
然后按 enter
,那么 $broadcast
是 keypress:58keypress:13
如果我按其他方式,我得到 keypress:13keypress:58
)
So if I have multiple keypresses, then I create the correct $broadcast
. The problem, however, becomes that the order matters now (i.e., if I press a
then enter
, then the $broadcast
is keypress:58keypress:13
and if I press the other way, I get keypress:13keypress:58
)
推荐答案
在我看来,广播使用的太多了.相反,也许使用自定义指令?这是一个用户按下 Shift+Tab 的例子,它会触发一个这样的事件:
Broadcast is used way too much in my opinion. Instead, maybe use a custom directive? This is an example of user pressing down Shift+Tab and it fires an event like so:
<input on-shift-tab="prevStep($event,'email')" />
app.directive('onShiftTab', function() {
return function(scope, element, attrs) {
var map = {9: false, 16: false};
element.on("keydown", function(event) {
if (event.which in map) {
map[event.which] = true;
if (map[9] && map[16]) {
scope.$apply(function(){
scope.$eval(attrs.onShiftTab, {'$event': event});
});
event.preventDefault();
}
}
});
element.on("keyup", function(event) {
if (event.which in map) {
map[event.keyCode] = false;
}
});
};
})
这篇关于AngularJS - 同时按下多个按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!