【问题标题】:Is it possible to listen for arrow keyspress using ng-keypress?是否可以使用 ng-keypress 监听箭头按键?
【发布时间】:2014-08-23 17:32:19
【问题描述】:

我正在尝试创建类似于 konami 代码“up,up,down,down,a,b,a,b, enter”的交互 -> 发生了一些事情。

是否可以使用 ng-keypress 监听箭头按键?它似乎不起作用?

html:

input( ng-keypress='changed($event)'  )

Js

$scope.changed = (evt) ->
    console.log(evt)

这不会注销箭头键事件?

我必须在窗口上推出自己的监听器吗?如果是这样,我怎样才能以角度实现这一目标?

【问题讨论】:

  • 我创建了demo 并且工作正常。
  • 我正在尝试检测箭头键。它确实工作得很好,但是你如何检测有人从输入字段中按下向上箭头

标签: javascript angularjs keypress event-listener


【解决方案1】:

DEMO

$scope.key = function($event){
    console.log($event.keyCode);
    if ($event.keyCode == 38)
        alert("up arrow");
    else if ($event.keyCode == 39)
        alert("right arrow");
    else if ($event.keyCode == 40)
        alert("down arrow");
    else if ($event.keyCode == 37)
        alert("left arrow");
}

编辑

将其从 ng-keypress 更改为 ng-keydown. DEMO

<input ng-keydown="key($event)" />

【讨论】:

  • 有趣的是,我在使用 google chrome 时没有收到任何警报?它适用于 Firefox 大声笑?
  • 无论如何都会将其标记为正确,但是您知道如何使 keyCodes 跨浏览器吗?
  • 我在 firefox 上测试过,所以让我试试 chrome。
  • 嗨,知道为什么我的 keyCode 中的值错误:(stackoverflow.com/questions/30128431/…
  • 啊,所以 keypress 已被弃用,我们现在应该使用 keyup
【解决方案2】:

您可以使用自定义指令来监听 keydown 和 keypressed 事件。我测试过的一个可能的实现如下:

var app = angular.module('app', []);

// a helper service to detect the arrow keys from the key codes
app.factory('keys', function() {
    var keysEnum = { left: 37, up: 38, right: 39, down: 40 };
    var theKeys =  [ keysEnum.left, keysEnum.up, keysEnum.right, keysEnum.down ];
    function isIn(val) {
        var isin = false
        if (theKeys.indexOf(val) >= 0) {
            isin = true;
        }
        return isin;
    }
    function keyFromCode(code) {
        var key = 'unknown';
        switch (code) {
            case 37:
                key = 'left';
                break;
            case 38:
                key = 'up';
                break;
            case 39:
                key = 'right';
                break;
            case 40:
                key = 'down';
                break;
        }
        return key;
    }
    return {
        isIn: isIn,
        keyFromCode: keyFromCode
    };
});

// custom directive to detect the arrow key pressed
app.directive('keypressed', [ 'keys', function (keys) {
    return function (scope, element, attrs) {
        // listen for the events keydown, keypress
        element.bind("keydown keypress", function (event) {
            var code = event.which;
            // if an arrow key is pressed then do something
            if(keys.isIn(code)) {
                console.log(keys.keyFromCode(code));
            }
        });
    };
}]);

你可以像这样使用上面的指令:

<span ng-app="app">
    <input keypressed />
</span>

从您发布的代码看来,您使用的是 html 模板引擎,因此在您的情况下,您可以使用如下指令:

input( keypressed )

【讨论】:

    猜你喜欢
    • 2014-07-05
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2022-07-26
    • 2011-02-28
    相关资源
    最近更新 更多