gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:57:59 25 4
gpt4 key购买 nike

我正在捕获这样的按键:

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

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

如何才能让单击某个键使光标转到输入字段:

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

最佳答案

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

在下面的示例中,只要按下 a 键盘按钮,input 就会获得焦点。我留下了评论,以便您可以根据需要进行修改(希望总体思路清晰):

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>

更新:acceptOn 回调中添加了 element 参数,以允许将目标与相同元素进行比较,因为我们想让用户在我们的例子中,输入这个 input 元素。

关于angularjs - 如何根据按键将光标定位在输入字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48483914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com