检测键盘按键输入

时间:2015-04-24 08:41:06

标签: html angularjs

目前我有一个检测用户输入文本并打印相应文本的表单,但我的问题是如果用户想要输入ctrl密钥,我该如何实现呢?

例如:

如果用户按下键a,它将会显示,但如果用户同时按下cntrl键,它也会显示。

摆弄here

<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>


<div ng-app="">

<p>Choose your control</p>
<p>Option : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

由于

3 个答案:

答案 0 :(得分:1)

您可以使用角度JS来回答控制键检测:

&#13;
&#13;
angular.module("mainModule", [])
  .controller("mainController", function ($scope)
  {
    // Initialization
    $scope.onKeyDownResult = "";
    $scope.onKeyUpResult = "";
    $scope.onKeyPressResult = "";

    // Utility functions

    var getKeyboardEventResult = function (keyEvent, keyEventDesc)
    {
      return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")";
    };

    // Event handlers
    $scope.onKeyDown = function ($event) {
      if($event.keyCode === 17)
        {
          $scope.name += " ctrl ";
          $scope.onKeyDownResult = getKeyboardEventResult($event, name);
        }
      else if($event.keyCode === 16)
        {
          $scope.name += " shift ";
          $scope.onKeyDownResult = getKeyboardEventResult($event, name);
        }
      else if($event.keyCode === 18)
        {
          $scope.name += " Alt ";
          $scope.onKeyDownResult = getKeyboardEventResult($event, name);
        }
      else
        {
      $scope.onKeyDownResult = getKeyboardEventResult($event, name);
        }
    };

  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>

<body ng-app="mainModule">
  <div ng-controller="mainController">
    <label>Type something:
      <input type="text"
             ng-keydown="onKeyDown($event)"
             ng-model="name" />
    </label><br />
    <p>KEY DOWN RESULT:<p>{{name}}<br />
    
  </div>
</body>
</html>
&#13;
&#13;
&#13;

希望它有所帮助。

答案 1 :(得分:0)

尝试使用“ng-keypress = check($ event)”,$ event对象有“keyCode”,检查keyCode并更新函数内的模型。 Ctrl是键码17.所以在你的功能中,你将检查这样的特定键:if($event.keyCode === 17){ $scope.model += " ctrl" }; 您可以在此处查看所有密钥代码:http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

答案 2 :(得分:0)

请参阅AngularJS键盘事件:http://www.angularjshub.com/examples/eventhandlers/keyboardevents/

您可以在输入框中使用这些事件来捕获密钥代码:

<input type="text"
ng-keydown="onKeyDown($event)"
ng-keyup="onKeyUp($event)"
ng-keypress="onKeyPress($event)" />