如何根据按键将光标定位在输入字段中?

时间:2022-04-23 08:44:41

I am capturing keypresses like this:

我正在捕捉这样的按键:

<div class="contentView"
     ng-keypress="phs.keyEnter($event)">

keyEnter = ($event): void => {
    var a = $event;

How can I make it so that clicking a key will make the cursor go to an input field:

如何使其单击一个键使光标转到输入字段:

 <input ng-change="phs.englishChange();"
               ng-model="phs.english"
               ng-model-options="{ debounce: 750 }"
               style="width:6rem;"
               type="text" />

2 个解决方案

#1


6  

I think directive can help us to have a more universal and re-usable solution to your problem, because it is the most good place to attach a specified behavior to that input element. So here is a custom doOnKeypress directive that accepts a key (doOnKeypress) and an optional callback (acceptOn) to check the target of the fired keypress event and a callback (onKeypress) that is going to be fired if all conditions are satisfied.

我认为指令可以帮助我们为您的问题提供更通用和可重用的解决方案,因为它是将指定行为附加到该输入元素的最佳位置。所以这里有一个自定义的doOnKeypress指令,它接受一个键(doOnKeypress)和一个可选的回调(acceptOn)来检查被触发的keypress事件的目标,以及一个在满足所有条件时将被触发的回调(onKeypress)。

In the example below the input will be focused whenever a keyboard button is pressed. I left the comments so you can modify it for your needs (hope the general idea is clear):

在下面的示例中,只要按下键盘按钮,输入就会聚焦。我留下了评论,因此您可以根据自己的需要对其进行修改(希望总体思路清晰):

angular.module("app", [])
    .controller("TestController", ["$scope", function ($scope) {
        $scope.acceptOn = function (target, element) {
            console.log(target);     // you can make any checks for target by passing this into a directive
            return element[0] !== target[0]; //target is not the same input element
        };
        $scope.focusOn = function (element) {
            element[0].focus(); // or whatever you want with element
        };
    }]).directive('doOnKeypress', ['$document', function ($document) {
    return {
        restrict: 'A',
        scope: {
            doOnKeypress: '@',
            acceptOn: '&?',
            onKeypress: '&'
        },
        link: function postLink(scope, element) {

            function keypress(e) {
                var target = angular.element(e.target);
                var targetIsAcceptable = angular.isFunction(scope.acceptOn) ? scope.acceptOn({
                    target: target,
                    element: element
                }) : true; // add the condition to test the target
                var specialKeyPressed = e.shiftKey || e.ctrlKey || e.altKey || e.metaKey; // in case you need to check any special keys

                if (targetIsAcceptable && !specialKeyPressed) {
                    var keyCode = e.which || e.keyCode;
                    var key = String.fromCharCode(keyCode);
                    if ("*" === scope.doOnKeypress || key.toLowerCase() === scope.doOnKeypress.toLowerCase()) {  // any check before focusing  (lets say * - is any key)
                        e.preventDefault(); // prevent from typing into the input
                        scope.onKeypress({element: element});
                    }
                }
            }

            $document.on('keypress', keypress);

            scope.$on('$destroy', function () {
                $document.off('keypress', keypress);
            });
        }
    };
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<body ng-app="app" class="">
  <div ng-controller="TestController" class='listen-to-keypress'>
   TestController

   <br/>
    
   <div>
   
    <input ng-change="phs.englishChange();"
               ng-model="phs.english"
               ng-model-options="{ debounce: 750 }"
               style="width:6rem;"
               do-on-keypress='A'
               accept-on='acceptOn(target, element)'
               on-keypress='focusOn(element)'
               type="text" />
   
   </div>

  </div>
</body>

UPDATE: added element argument to the acceptOn callback to allow to compare target with the same element, since we want to let the user typing into this input element in our case.

更新:为acceptOn回调添加了元素参数,以允许将目标与同一元素进行比较,因为我们希望让用户在我们的情况下输入这个输入元素。

#2


0  

HTML

<input value="_sample input value" ng-click="getCur_Pos($e)" ng-keyup="getCur_Pos($e)"/>
    <div> Cursor Pos : <b ng-bind="curPos_Val"></b></div>

SCRIPT

$scope.getCur_Pos = function($e) {
   $scope.doCar_Position($e.target);  
};

$scope.doCar_Position = function(o_Fld) {
var _Crt_Pos = 0;
if (o_Fld.selectionStart || o_Fld.selectionStart == '0')
  _Crt_Pos = o_Fld.selectionStart;
// Return results
$scope.curPos_Val = _Crt_Pos;

};

#1


6  

I think directive can help us to have a more universal and re-usable solution to your problem, because it is the most good place to attach a specified behavior to that input element. So here is a custom doOnKeypress directive that accepts a key (doOnKeypress) and an optional callback (acceptOn) to check the target of the fired keypress event and a callback (onKeypress) that is going to be fired if all conditions are satisfied.

我认为指令可以帮助我们为您的问题提供更通用和可重用的解决方案,因为它是将指定行为附加到该输入元素的最佳位置。所以这里有一个自定义的doOnKeypress指令,它接受一个键(doOnKeypress)和一个可选的回调(acceptOn)来检查被触发的keypress事件的目标,以及一个在满足所有条件时将被触发的回调(onKeypress)。

In the example below the input will be focused whenever a keyboard button is pressed. I left the comments so you can modify it for your needs (hope the general idea is clear):

在下面的示例中,只要按下键盘按钮,输入就会聚焦。我留下了评论,因此您可以根据自己的需要对其进行修改(希望总体思路清晰):

angular.module("app", [])
    .controller("TestController", ["$scope", function ($scope) {
        $scope.acceptOn = function (target, element) {
            console.log(target);     // you can make any checks for target by passing this into a directive
            return element[0] !== target[0]; //target is not the same input element
        };
        $scope.focusOn = function (element) {
            element[0].focus(); // or whatever you want with element
        };
    }]).directive('doOnKeypress', ['$document', function ($document) {
    return {
        restrict: 'A',
        scope: {
            doOnKeypress: '@',
            acceptOn: '&?',
            onKeypress: '&'
        },
        link: function postLink(scope, element) {

            function keypress(e) {
                var target = angular.element(e.target);
                var targetIsAcceptable = angular.isFunction(scope.acceptOn) ? scope.acceptOn({
                    target: target,
                    element: element
                }) : true; // add the condition to test the target
                var specialKeyPressed = e.shiftKey || e.ctrlKey || e.altKey || e.metaKey; // in case you need to check any special keys

                if (targetIsAcceptable && !specialKeyPressed) {
                    var keyCode = e.which || e.keyCode;
                    var key = String.fromCharCode(keyCode);
                    if ("*" === scope.doOnKeypress || key.toLowerCase() === scope.doOnKeypress.toLowerCase()) {  // any check before focusing  (lets say * - is any key)
                        e.preventDefault(); // prevent from typing into the input
                        scope.onKeypress({element: element});
                    }
                }
            }

            $document.on('keypress', keypress);

            scope.$on('$destroy', function () {
                $document.off('keypress', keypress);
            });
        }
    };
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<body ng-app="app" class="">
  <div ng-controller="TestController" class='listen-to-keypress'>
   TestController

   <br/>
    
   <div>
   
    <input ng-change="phs.englishChange();"
               ng-model="phs.english"
               ng-model-options="{ debounce: 750 }"
               style="width:6rem;"
               do-on-keypress='A'
               accept-on='acceptOn(target, element)'
               on-keypress='focusOn(element)'
               type="text" />
   
   </div>

  </div>
</body>

UPDATE: added element argument to the acceptOn callback to allow to compare target with the same element, since we want to let the user typing into this input element in our case.

更新:为acceptOn回调添加了元素参数,以允许将目标与同一元素进行比较,因为我们希望让用户在我们的情况下输入这个输入元素。

#2


0  

HTML

<input value="_sample input value" ng-click="getCur_Pos($e)" ng-keyup="getCur_Pos($e)"/>
    <div> Cursor Pos : <b ng-bind="curPos_Val"></b></div>

SCRIPT

$scope.getCur_Pos = function($e) {
   $scope.doCar_Position($e.target);  
};

$scope.doCar_Position = function(o_Fld) {
var _Crt_Pos = 0;
if (o_Fld.selectionStart || o_Fld.selectionStart == '0')
  _Crt_Pos = o_Fld.selectionStart;
// Return results
$scope.curPos_Val = _Crt_Pos;

};